babylon.max.js 3.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var KeyboardEventTypes = (function () {
  20. function KeyboardEventTypes() {
  21. }
  22. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  23. get: function () {
  24. return KeyboardEventTypes._KEYDOWN;
  25. },
  26. enumerable: true,
  27. configurable: true
  28. });
  29. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  30. get: function () {
  31. return KeyboardEventTypes._KEYUP;
  32. },
  33. enumerable: true,
  34. configurable: true
  35. });
  36. KeyboardEventTypes._KEYDOWN = 0x01;
  37. KeyboardEventTypes._KEYUP = 0x02;
  38. return KeyboardEventTypes;
  39. }());
  40. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  41. var KeyboardInfo = (function () {
  42. function KeyboardInfo(type, event) {
  43. this.type = type;
  44. this.event = event;
  45. }
  46. return KeyboardInfo;
  47. }());
  48. BABYLON.KeyboardInfo = KeyboardInfo;
  49. /**
  50. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  51. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  52. */
  53. var KeyboardInfoPre = (function (_super) {
  54. __extends(KeyboardInfoPre, _super);
  55. function KeyboardInfoPre(type, event) {
  56. var _this = _super.call(this, type, event) || this;
  57. _this.skipOnPointerObservable = false;
  58. return _this;
  59. }
  60. return KeyboardInfoPre;
  61. }(KeyboardInfo));
  62. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  63. })(BABYLON || (BABYLON = {}));
  64. //# sourceMappingURL=babylon.keyboardEvents.js.map
  65. var BABYLON;
  66. (function (BABYLON) {
  67. var PointerEventTypes = (function () {
  68. function PointerEventTypes() {
  69. }
  70. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  71. get: function () {
  72. return PointerEventTypes._POINTERDOWN;
  73. },
  74. enumerable: true,
  75. configurable: true
  76. });
  77. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  78. get: function () {
  79. return PointerEventTypes._POINTERUP;
  80. },
  81. enumerable: true,
  82. configurable: true
  83. });
  84. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  85. get: function () {
  86. return PointerEventTypes._POINTERMOVE;
  87. },
  88. enumerable: true,
  89. configurable: true
  90. });
  91. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  92. get: function () {
  93. return PointerEventTypes._POINTERWHEEL;
  94. },
  95. enumerable: true,
  96. configurable: true
  97. });
  98. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  99. get: function () {
  100. return PointerEventTypes._POINTERPICK;
  101. },
  102. enumerable: true,
  103. configurable: true
  104. });
  105. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  106. get: function () {
  107. return PointerEventTypes._POINTERTAP;
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  113. get: function () {
  114. return PointerEventTypes._POINTERDOUBLETAP;
  115. },
  116. enumerable: true,
  117. configurable: true
  118. });
  119. PointerEventTypes._POINTERDOWN = 0x01;
  120. PointerEventTypes._POINTERUP = 0x02;
  121. PointerEventTypes._POINTERMOVE = 0x04;
  122. PointerEventTypes._POINTERWHEEL = 0x08;
  123. PointerEventTypes._POINTERPICK = 0x10;
  124. PointerEventTypes._POINTERTAP = 0x20;
  125. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  126. return PointerEventTypes;
  127. }());
  128. BABYLON.PointerEventTypes = PointerEventTypes;
  129. var PointerInfoBase = (function () {
  130. function PointerInfoBase(type, event) {
  131. this.type = type;
  132. this.event = event;
  133. }
  134. return PointerInfoBase;
  135. }());
  136. BABYLON.PointerInfoBase = PointerInfoBase;
  137. /**
  138. * This class is used to store pointer related info for the onPrePointerObservable event.
  139. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  140. */
  141. var PointerInfoPre = (function (_super) {
  142. __extends(PointerInfoPre, _super);
  143. function PointerInfoPre(type, event, localX, localY) {
  144. var _this = _super.call(this, type, event) || this;
  145. _this.skipOnPointerObservable = false;
  146. _this.localPosition = new BABYLON.Vector2(localX, localY);
  147. return _this;
  148. }
  149. return PointerInfoPre;
  150. }(PointerInfoBase));
  151. BABYLON.PointerInfoPre = PointerInfoPre;
  152. /**
  153. * This type contains all the data related to a pointer event in Babylon.js.
  154. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  155. */
  156. var PointerInfo = (function (_super) {
  157. __extends(PointerInfo, _super);
  158. function PointerInfo(type, event, pickInfo) {
  159. var _this = _super.call(this, type, event) || this;
  160. _this.pickInfo = pickInfo;
  161. return _this;
  162. }
  163. return PointerInfo;
  164. }(PointerInfoBase));
  165. BABYLON.PointerInfo = PointerInfo;
  166. })(BABYLON || (BABYLON = {}));
  167. //# sourceMappingURL=babylon.pointerEvents.js.map
  168. var BABYLON;
  169. (function (BABYLON) {
  170. BABYLON.ToGammaSpace = 1 / 2.2;
  171. BABYLON.ToLinearSpace = 2.2;
  172. BABYLON.Epsilon = 0.001;
  173. var Color3 = (function () {
  174. /**
  175. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  176. */
  177. function Color3(r, g, b) {
  178. if (r === void 0) { r = 0; }
  179. if (g === void 0) { g = 0; }
  180. if (b === void 0) { b = 0; }
  181. this.r = r;
  182. this.g = g;
  183. this.b = b;
  184. }
  185. /**
  186. * Returns a string with the Color3 current values.
  187. */
  188. Color3.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  190. };
  191. /**
  192. * Returns the string "Color3".
  193. */
  194. Color3.prototype.getClassName = function () {
  195. return "Color3";
  196. };
  197. /**
  198. * Returns the Color3 hash code.
  199. */
  200. Color3.prototype.getHashCode = function () {
  201. var hash = this.r || 0;
  202. hash = (hash * 397) ^ (this.g || 0);
  203. hash = (hash * 397) ^ (this.b || 0);
  204. return hash;
  205. };
  206. // Operators
  207. /**
  208. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  209. * Returns the Color3.
  210. */
  211. Color3.prototype.toArray = function (array, index) {
  212. if (index === undefined) {
  213. index = 0;
  214. }
  215. array[index] = this.r;
  216. array[index + 1] = this.g;
  217. array[index + 2] = this.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color4 object from the current Color3 and the passed alpha.
  222. */
  223. Color3.prototype.toColor4 = function (alpha) {
  224. if (alpha === void 0) { alpha = 1; }
  225. return new Color4(this.r, this.g, this.b, alpha);
  226. };
  227. /**
  228. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  229. */
  230. Color3.prototype.asArray = function () {
  231. var result = [];
  232. this.toArray(result, 0);
  233. return result;
  234. };
  235. /**
  236. * Returns the luminance value (float).
  237. */
  238. Color3.prototype.toLuminance = function () {
  239. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  240. };
  241. /**
  242. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  243. * Returns this new object.
  244. */
  245. Color3.prototype.multiply = function (otherColor) {
  246. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  247. };
  248. /**
  249. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  250. * Returns the current Color3.
  251. */
  252. Color3.prototype.multiplyToRef = function (otherColor, result) {
  253. result.r = this.r * otherColor.r;
  254. result.g = this.g * otherColor.g;
  255. result.b = this.b * otherColor.b;
  256. return this;
  257. };
  258. /**
  259. * Boolean : True if the rgb values are equal to the passed ones.
  260. */
  261. Color3.prototype.equals = function (otherColor) {
  262. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  263. };
  264. /**
  265. * Boolean : True if the rgb values are equal to the passed ones.
  266. */
  267. Color3.prototype.equalsFloats = function (r, g, b) {
  268. return this.r === r && this.g === g && this.b === b;
  269. };
  270. /**
  271. * Multiplies in place each rgb value by scale.
  272. * Returns the updated Color3.
  273. */
  274. Color3.prototype.scale = function (scale) {
  275. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  276. };
  277. /**
  278. * Multiplies the rgb values by scale and stores the result into "result".
  279. * Returns the unmodified current Color3.
  280. */
  281. Color3.prototype.scaleToRef = function (scale, result) {
  282. result.r = this.r * scale;
  283. result.g = this.g * scale;
  284. result.b = this.b * scale;
  285. return this;
  286. };
  287. /**
  288. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  289. */
  290. Color3.prototype.add = function (otherColor) {
  291. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  292. };
  293. /**
  294. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  295. * Returns the unmodified current Color3.
  296. */
  297. Color3.prototype.addToRef = function (otherColor, result) {
  298. result.r = this.r + otherColor.r;
  299. result.g = this.g + otherColor.g;
  300. result.b = this.b + otherColor.b;
  301. return this;
  302. };
  303. /**
  304. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  305. */
  306. Color3.prototype.subtract = function (otherColor) {
  307. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  308. };
  309. /**
  310. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  311. * Returns the unmodified current Color3.
  312. */
  313. Color3.prototype.subtractToRef = function (otherColor, result) {
  314. result.r = this.r - otherColor.r;
  315. result.g = this.g - otherColor.g;
  316. result.b = this.b - otherColor.b;
  317. return this;
  318. };
  319. /**
  320. * Returns a new Color3 copied the current one.
  321. */
  322. Color3.prototype.clone = function () {
  323. return new Color3(this.r, this.g, this.b);
  324. };
  325. /**
  326. * Copies the rgb values from the source in the current Color3.
  327. * Returns the updated Color3.
  328. */
  329. Color3.prototype.copyFrom = function (source) {
  330. this.r = source.r;
  331. this.g = source.g;
  332. this.b = source.b;
  333. return this;
  334. };
  335. /**
  336. * Updates the Color3 rgb values from the passed floats.
  337. * Returns the Color3.
  338. */
  339. Color3.prototype.copyFromFloats = function (r, g, b) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. return this;
  344. };
  345. /**
  346. * Updates the Color3 rgb values from the passed floats.
  347. * Returns the Color3.
  348. */
  349. Color3.prototype.set = function (r, g, b) {
  350. return this.copyFromFloats(r, g, b);
  351. };
  352. /**
  353. * Returns the Color3 hexadecimal code as a string.
  354. */
  355. Color3.prototype.toHexString = function () {
  356. var intR = (this.r * 255) | 0;
  357. var intG = (this.g * 255) | 0;
  358. var intB = (this.b * 255) | 0;
  359. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  360. };
  361. /**
  362. * Returns a new Color3 converted to linear space.
  363. */
  364. Color3.prototype.toLinearSpace = function () {
  365. var convertedColor = new Color3();
  366. this.toLinearSpaceToRef(convertedColor);
  367. return convertedColor;
  368. };
  369. /**
  370. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  371. * Returns the unmodified Color3.
  372. */
  373. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  374. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  375. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  376. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color3 converted to gamma space.
  381. */
  382. Color3.prototype.toGammaSpace = function () {
  383. var convertedColor = new Color3();
  384. this.toGammaSpaceToRef(convertedColor);
  385. return convertedColor;
  386. };
  387. /**
  388. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  389. * Returns the unmodified Color3.
  390. */
  391. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  392. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  393. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  394. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  395. return this;
  396. };
  397. // Statics
  398. /**
  399. * Creates a new Color3 from the string containing valid hexadecimal values.
  400. */
  401. Color3.FromHexString = function (hex) {
  402. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  403. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  404. return new Color3(0, 0, 0);
  405. }
  406. var r = parseInt(hex.substring(1, 3), 16);
  407. var g = parseInt(hex.substring(3, 5), 16);
  408. var b = parseInt(hex.substring(5, 7), 16);
  409. return Color3.FromInts(r, g, b);
  410. };
  411. /**
  412. * Creates a new Vector3 from the startind index of the passed array.
  413. */
  414. Color3.FromArray = function (array, offset) {
  415. if (offset === void 0) { offset = 0; }
  416. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  417. };
  418. /**
  419. * Creates a new Color3 from integer values ( < 256).
  420. */
  421. Color3.FromInts = function (r, g, b) {
  422. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  423. };
  424. /**
  425. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  426. */
  427. Color3.Lerp = function (start, end, amount) {
  428. var r = start.r + ((end.r - start.r) * amount);
  429. var g = start.g + ((end.g - start.g) * amount);
  430. var b = start.b + ((end.b - start.b) * amount);
  431. return new Color3(r, g, b);
  432. };
  433. Color3.Red = function () { return new Color3(1, 0, 0); };
  434. Color3.Green = function () { return new Color3(0, 1, 0); };
  435. Color3.Blue = function () { return new Color3(0, 0, 1); };
  436. Color3.Black = function () { return new Color3(0, 0, 0); };
  437. Color3.White = function () { return new Color3(1, 1, 1); };
  438. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  439. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  440. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  441. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  442. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  443. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  444. return Color3;
  445. }());
  446. BABYLON.Color3 = Color3;
  447. var Color4 = (function () {
  448. /**
  449. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  450. */
  451. function Color4(r, g, b, a) {
  452. if (r === void 0) { r = 0; }
  453. if (g === void 0) { g = 0; }
  454. if (b === void 0) { b = 0; }
  455. if (a === void 0) { a = 1; }
  456. this.r = r;
  457. this.g = g;
  458. this.b = b;
  459. this.a = a;
  460. }
  461. // Operators
  462. /**
  463. * Adds in place the passed Color4 values to the current Color4.
  464. * Returns the updated Color4.
  465. */
  466. Color4.prototype.addInPlace = function (right) {
  467. this.r += right.r;
  468. this.g += right.g;
  469. this.b += right.b;
  470. this.a += right.a;
  471. return this;
  472. };
  473. /**
  474. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  475. */
  476. Color4.prototype.asArray = function () {
  477. var result = [];
  478. this.toArray(result, 0);
  479. return result;
  480. };
  481. /**
  482. * Stores from the starting index in the passed array the Color4 successive values.
  483. * Returns the Color4.
  484. */
  485. Color4.prototype.toArray = function (array, index) {
  486. if (index === undefined) {
  487. index = 0;
  488. }
  489. array[index] = this.r;
  490. array[index + 1] = this.g;
  491. array[index + 2] = this.b;
  492. array[index + 3] = this.a;
  493. return this;
  494. };
  495. /**
  496. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  497. */
  498. Color4.prototype.add = function (right) {
  499. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  500. };
  501. /**
  502. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  503. */
  504. Color4.prototype.subtract = function (right) {
  505. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  506. };
  507. /**
  508. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  509. * Returns the Color4.
  510. */
  511. Color4.prototype.subtractToRef = function (right, result) {
  512. result.r = this.r - right.r;
  513. result.g = this.g - right.g;
  514. result.b = this.b - right.b;
  515. result.a = this.a - right.a;
  516. return this;
  517. };
  518. /**
  519. * Creates a new Color4 with the current Color4 values multiplied by scale.
  520. */
  521. Color4.prototype.scale = function (scale) {
  522. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  523. };
  524. /**
  525. * Multiplies the current Color4 values by scale and stores the result in "result".
  526. * Returns the Color4.
  527. */
  528. Color4.prototype.scaleToRef = function (scale, result) {
  529. result.r = this.r * scale;
  530. result.g = this.g * scale;
  531. result.b = this.b * scale;
  532. result.a = this.a * scale;
  533. return this;
  534. };
  535. /**
  536. * Multipy an RGBA Color4 value by another and return a new Color4 object
  537. * @param color The Color4 (RGBA) value to multiply by
  538. * @returns A new Color4.
  539. */
  540. Color4.prototype.multiply = function (color) {
  541. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  542. };
  543. /**
  544. * Multipy an RGBA Color4 value by another and push the result in a reference value
  545. * @param color The Color4 (RGBA) value to multiply by
  546. * @param result The Color4 (RGBA) to fill the result in
  547. * @returns the result Color4.
  548. */
  549. Color4.prototype.multiplyToRef = function (color, result) {
  550. result.r = this.r * color.r;
  551. result.g = this.g * color.g;
  552. result.b = this.b * color.b;
  553. result.a = this.a * color.a;
  554. return result;
  555. };
  556. /**
  557. * Returns a string with the Color4 values.
  558. */
  559. Color4.prototype.toString = function () {
  560. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  561. };
  562. /**
  563. * Returns the string "Color4"
  564. */
  565. Color4.prototype.getClassName = function () {
  566. return "Color4";
  567. };
  568. /**
  569. * Return the Color4 hash code as a number.
  570. */
  571. Color4.prototype.getHashCode = function () {
  572. var hash = this.r || 0;
  573. hash = (hash * 397) ^ (this.g || 0);
  574. hash = (hash * 397) ^ (this.b || 0);
  575. hash = (hash * 397) ^ (this.a || 0);
  576. return hash;
  577. };
  578. /**
  579. * Creates a new Color4 copied from the current one.
  580. */
  581. Color4.prototype.clone = function () {
  582. return new Color4(this.r, this.g, this.b, this.a);
  583. };
  584. /**
  585. * Copies the passed Color4 values into the current one.
  586. * Returns the updated Color4.
  587. */
  588. Color4.prototype.copyFrom = function (source) {
  589. this.r = source.r;
  590. this.g = source.g;
  591. this.b = source.b;
  592. this.a = source.a;
  593. return this;
  594. };
  595. /**
  596. * Copies the passed float values into the current one.
  597. * Returns the updated Color4.
  598. */
  599. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  600. this.r = r;
  601. this.g = g;
  602. this.b = b;
  603. this.a = a;
  604. return this;
  605. };
  606. /**
  607. * Copies the passed float values into the current one.
  608. * Returns the updated Color4.
  609. */
  610. Color4.prototype.set = function (r, g, b, a) {
  611. return this.copyFromFloats(r, g, b, a);
  612. };
  613. /**
  614. * Returns a string containing the hexadecimal Color4 code.
  615. */
  616. Color4.prototype.toHexString = function () {
  617. var intR = (this.r * 255) | 0;
  618. var intG = (this.g * 255) | 0;
  619. var intB = (this.b * 255) | 0;
  620. var intA = (this.a * 255) | 0;
  621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  622. };
  623. /**
  624. * Returns a new Color4 converted to linear space.
  625. */
  626. Color4.prototype.toLinearSpace = function () {
  627. var convertedColor = new Color4();
  628. this.toLinearSpaceToRef(convertedColor);
  629. return convertedColor;
  630. };
  631. /**
  632. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  633. * Returns the unmodified Color4.
  634. */
  635. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  636. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  637. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  638. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  639. convertedColor.a = this.a;
  640. return this;
  641. };
  642. /**
  643. * Returns a new Color4 converted to gamma space.
  644. */
  645. Color4.prototype.toGammaSpace = function () {
  646. var convertedColor = new Color4();
  647. this.toGammaSpaceToRef(convertedColor);
  648. return convertedColor;
  649. };
  650. /**
  651. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  652. * Returns the unmodified Color4.
  653. */
  654. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  655. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  656. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  657. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  658. convertedColor.a = this.a;
  659. return this;
  660. };
  661. // Statics
  662. /**
  663. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  664. */
  665. Color4.FromHexString = function (hex) {
  666. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  667. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  668. return new Color4(0.0, 0.0, 0.0, 0.0);
  669. }
  670. var r = parseInt(hex.substring(1, 3), 16);
  671. var g = parseInt(hex.substring(3, 5), 16);
  672. var b = parseInt(hex.substring(5, 7), 16);
  673. var a = parseInt(hex.substring(7, 9), 16);
  674. return Color4.FromInts(r, g, b, a);
  675. };
  676. /**
  677. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  678. */
  679. Color4.Lerp = function (left, right, amount) {
  680. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  681. Color4.LerpToRef(left, right, amount, result);
  682. return result;
  683. };
  684. /**
  685. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  686. */
  687. Color4.LerpToRef = function (left, right, amount, result) {
  688. result.r = left.r + (right.r - left.r) * amount;
  689. result.g = left.g + (right.g - left.g) * amount;
  690. result.b = left.b + (right.b - left.b) * amount;
  691. result.a = left.a + (right.a - left.a) * amount;
  692. };
  693. /**
  694. * Creates a new Color4 from the starting index element of the passed array.
  695. */
  696. Color4.FromArray = function (array, offset) {
  697. if (offset === void 0) { offset = 0; }
  698. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  699. };
  700. /**
  701. * Creates a new Color4 from the passed integers ( < 256 ).
  702. */
  703. Color4.FromInts = function (r, g, b, a) {
  704. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  705. };
  706. Color4.CheckColors4 = function (colors, count) {
  707. // Check if color3 was used
  708. if (colors.length === count * 3) {
  709. var colors4 = [];
  710. for (var index = 0; index < colors.length; index += 3) {
  711. var newIndex = (index / 3) * 4;
  712. colors4[newIndex] = colors[index];
  713. colors4[newIndex + 1] = colors[index + 1];
  714. colors4[newIndex + 2] = colors[index + 2];
  715. colors4[newIndex + 3] = 1.0;
  716. }
  717. return colors4;
  718. }
  719. return colors;
  720. };
  721. return Color4;
  722. }());
  723. BABYLON.Color4 = Color4;
  724. var Vector2 = (function () {
  725. /**
  726. * Creates a new Vector2 from the passed x and y coordinates.
  727. */
  728. function Vector2(x, y) {
  729. this.x = x;
  730. this.y = y;
  731. }
  732. /**
  733. * Returns a string with the Vector2 coordinates.
  734. */
  735. Vector2.prototype.toString = function () {
  736. return "{X: " + this.x + " Y:" + this.y + "}";
  737. };
  738. /**
  739. * Returns the string "Vector2"
  740. */
  741. Vector2.prototype.getClassName = function () {
  742. return "Vector2";
  743. };
  744. /**
  745. * Returns the Vector2 hash code as a number.
  746. */
  747. Vector2.prototype.getHashCode = function () {
  748. var hash = this.x || 0;
  749. hash = (hash * 397) ^ (this.y || 0);
  750. return hash;
  751. };
  752. // Operators
  753. /**
  754. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  755. * Returns the Vector2.
  756. */
  757. Vector2.prototype.toArray = function (array, index) {
  758. if (index === void 0) { index = 0; }
  759. array[index] = this.x;
  760. array[index + 1] = this.y;
  761. return this;
  762. };
  763. /**
  764. * Returns a new array with 2 elements : the Vector2 coordinates.
  765. */
  766. Vector2.prototype.asArray = function () {
  767. var result = [];
  768. this.toArray(result, 0);
  769. return result;
  770. };
  771. /**
  772. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  773. * Returns the updated Vector2.
  774. */
  775. Vector2.prototype.copyFrom = function (source) {
  776. this.x = source.x;
  777. this.y = source.y;
  778. return this;
  779. };
  780. /**
  781. * Sets the Vector2 coordinates with the passed floats.
  782. * Returns the updated Vector2.
  783. */
  784. Vector2.prototype.copyFromFloats = function (x, y) {
  785. this.x = x;
  786. this.y = y;
  787. return this;
  788. };
  789. /**
  790. * Sets the Vector2 coordinates with the passed floats.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.set = function (x, y) {
  794. return this.copyFromFloats(x, y);
  795. };
  796. /**
  797. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  798. */
  799. Vector2.prototype.add = function (otherVector) {
  800. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  801. };
  802. /**
  803. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  804. * Returns the Vector2.
  805. */
  806. Vector2.prototype.addToRef = function (otherVector, result) {
  807. result.x = this.x + otherVector.x;
  808. result.y = this.y + otherVector.y;
  809. return this;
  810. };
  811. /**
  812. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  813. * Returns the updated Vector2.
  814. */
  815. Vector2.prototype.addInPlace = function (otherVector) {
  816. this.x += otherVector.x;
  817. this.y += otherVector.y;
  818. return this;
  819. };
  820. /**
  821. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  822. */
  823. Vector2.prototype.addVector3 = function (otherVector) {
  824. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  825. };
  826. /**
  827. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  828. */
  829. Vector2.prototype.subtract = function (otherVector) {
  830. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  831. };
  832. /**
  833. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  834. * Returns the Vector2.
  835. */
  836. Vector2.prototype.subtractToRef = function (otherVector, result) {
  837. result.x = this.x - otherVector.x;
  838. result.y = this.y - otherVector.y;
  839. return this;
  840. };
  841. /**
  842. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  843. * Returns the updated Vector2.
  844. */
  845. Vector2.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. return this;
  849. };
  850. /**
  851. * Multiplies in place the current Vector2 coordinates by the passed ones.
  852. * Returns the updated Vector2.
  853. */
  854. Vector2.prototype.multiplyInPlace = function (otherVector) {
  855. this.x *= otherVector.x;
  856. this.y *= otherVector.y;
  857. return this;
  858. };
  859. /**
  860. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  861. */
  862. Vector2.prototype.multiply = function (otherVector) {
  863. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  864. };
  865. /**
  866. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  867. * Returns the Vector2.
  868. */
  869. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  870. result.x = this.x * otherVector.x;
  871. result.y = this.y * otherVector.y;
  872. return this;
  873. };
  874. /**
  875. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  876. */
  877. Vector2.prototype.multiplyByFloats = function (x, y) {
  878. return new Vector2(this.x * x, this.y * y);
  879. };
  880. /**
  881. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  882. */
  883. Vector2.prototype.divide = function (otherVector) {
  884. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  885. };
  886. /**
  887. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  888. * Returns the Vector2.
  889. */
  890. Vector2.prototype.divideToRef = function (otherVector, result) {
  891. result.x = this.x / otherVector.x;
  892. result.y = this.y / otherVector.y;
  893. return this;
  894. };
  895. /**
  896. * Returns a new Vector2 with current Vector2 negated coordinates.
  897. */
  898. Vector2.prototype.negate = function () {
  899. return new Vector2(-this.x, -this.y);
  900. };
  901. /**
  902. * Multiply the Vector2 coordinates by scale.
  903. * Returns the updated Vector2.
  904. */
  905. Vector2.prototype.scaleInPlace = function (scale) {
  906. this.x *= scale;
  907. this.y *= scale;
  908. return this;
  909. };
  910. /**
  911. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  912. */
  913. Vector2.prototype.scale = function (scale) {
  914. return new Vector2(this.x * scale, this.y * scale);
  915. };
  916. /**
  917. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  918. */
  919. Vector2.prototype.equals = function (otherVector) {
  920. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  921. };
  922. /**
  923. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  924. */
  925. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  928. };
  929. // Properties
  930. /**
  931. * Returns the vector length (float).
  932. */
  933. Vector2.prototype.length = function () {
  934. return Math.sqrt(this.x * this.x + this.y * this.y);
  935. };
  936. /**
  937. * Returns the vector squared length (float);
  938. */
  939. Vector2.prototype.lengthSquared = function () {
  940. return (this.x * this.x + this.y * this.y);
  941. };
  942. // Methods
  943. /**
  944. * Normalize the vector.
  945. * Returns the updated Vector2.
  946. */
  947. Vector2.prototype.normalize = function () {
  948. var len = this.length();
  949. if (len === 0)
  950. return this;
  951. var num = 1.0 / len;
  952. this.x *= num;
  953. this.y *= num;
  954. return this;
  955. };
  956. /**
  957. * Returns a new Vector2 copied from the Vector2.
  958. */
  959. Vector2.prototype.clone = function () {
  960. return new Vector2(this.x, this.y);
  961. };
  962. // Statics
  963. /**
  964. * Returns a new Vector2(0, 0)
  965. */
  966. Vector2.Zero = function () {
  967. return new Vector2(0, 0);
  968. };
  969. /**
  970. * Returns a new Vector2(1, 1)
  971. */
  972. Vector2.One = function () {
  973. return new Vector2(1, 1);
  974. };
  975. /**
  976. * Returns a new Vector2 set from the passed index element of the passed array.
  977. */
  978. Vector2.FromArray = function (array, offset) {
  979. if (offset === void 0) { offset = 0; }
  980. return new Vector2(array[offset], array[offset + 1]);
  981. };
  982. /**
  983. * Sets "result" from the passed index element of the passed array.
  984. */
  985. Vector2.FromArrayToRef = function (array, offset, result) {
  986. result.x = array[offset];
  987. result.y = array[offset + 1];
  988. };
  989. /**
  990. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  991. */
  992. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  993. var squared = amount * amount;
  994. var cubed = amount * squared;
  995. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  996. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  997. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  998. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  999. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1000. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1001. return new Vector2(x, y);
  1002. };
  1003. /**
  1004. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1005. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1006. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1007. */
  1008. Vector2.Clamp = function (value, min, max) {
  1009. var x = value.x;
  1010. x = (x > max.x) ? max.x : x;
  1011. x = (x < min.x) ? min.x : x;
  1012. var y = value.y;
  1013. y = (y > max.y) ? max.y : y;
  1014. y = (y < min.y) ? min.y : y;
  1015. return new Vector2(x, y);
  1016. };
  1017. /**
  1018. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1019. */
  1020. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1021. var squared = amount * amount;
  1022. var cubed = amount * squared;
  1023. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1024. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1025. var part3 = (cubed - (2.0 * squared)) + amount;
  1026. var part4 = cubed - squared;
  1027. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1028. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1029. return new Vector2(x, y);
  1030. };
  1031. /**
  1032. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1033. */
  1034. Vector2.Lerp = function (start, end, amount) {
  1035. var x = start.x + ((end.x - start.x) * amount);
  1036. var y = start.y + ((end.y - start.y) * amount);
  1037. return new Vector2(x, y);
  1038. };
  1039. /**
  1040. * Returns the dot product (float) of the vector "left" and the vector "right".
  1041. */
  1042. Vector2.Dot = function (left, right) {
  1043. return left.x * right.x + left.y * right.y;
  1044. };
  1045. /**
  1046. * Returns a new Vector2 equal to the normalized passed vector.
  1047. */
  1048. Vector2.Normalize = function (vector) {
  1049. var newVector = vector.clone();
  1050. newVector.normalize();
  1051. return newVector;
  1052. };
  1053. /**
  1054. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1055. */
  1056. Vector2.Minimize = function (left, right) {
  1057. var x = (left.x < right.x) ? left.x : right.x;
  1058. var y = (left.y < right.y) ? left.y : right.y;
  1059. return new Vector2(x, y);
  1060. };
  1061. /**
  1062. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1063. */
  1064. Vector2.Maximize = function (left, right) {
  1065. var x = (left.x > right.x) ? left.x : right.x;
  1066. var y = (left.y > right.y) ? left.y : right.y;
  1067. return new Vector2(x, y);
  1068. };
  1069. /**
  1070. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1071. */
  1072. Vector2.Transform = function (vector, transformation) {
  1073. var r = Vector2.Zero();
  1074. Vector2.TransformToRef(vector, transformation, r);
  1075. return r;
  1076. };
  1077. /**
  1078. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1079. */
  1080. Vector2.TransformToRef = function (vector, transformation, result) {
  1081. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1082. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1083. result.x = x;
  1084. result.y = y;
  1085. };
  1086. /**
  1087. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1088. */
  1089. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1090. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1091. var sign = a < 0 ? -1 : 1;
  1092. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1093. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1094. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1095. };
  1096. /**
  1097. * Returns the distance (float) between the vectors "value1" and "value2".
  1098. */
  1099. Vector2.Distance = function (value1, value2) {
  1100. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1101. };
  1102. /**
  1103. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1104. */
  1105. Vector2.DistanceSquared = function (value1, value2) {
  1106. var x = value1.x - value2.x;
  1107. var y = value1.y - value2.y;
  1108. return (x * x) + (y * y);
  1109. };
  1110. /**
  1111. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1112. */
  1113. Vector2.Center = function (value1, value2) {
  1114. var center = value1.add(value2);
  1115. center.scaleInPlace(0.5);
  1116. return center;
  1117. };
  1118. /**
  1119. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1120. */
  1121. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1122. var l2 = Vector2.DistanceSquared(segA, segB);
  1123. if (l2 === 0.0) {
  1124. return Vector2.Distance(p, segA);
  1125. }
  1126. var v = segB.subtract(segA);
  1127. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1128. var proj = segA.add(v.multiplyByFloats(t, t));
  1129. return Vector2.Distance(p, proj);
  1130. };
  1131. return Vector2;
  1132. }());
  1133. BABYLON.Vector2 = Vector2;
  1134. var Vector3 = (function () {
  1135. /**
  1136. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1137. * A Vector3 is the main object used in 3D geometry.
  1138. * It can represent etiher the coordinates of a point the space, either a direction.
  1139. */
  1140. function Vector3(x, y, z) {
  1141. this.x = x;
  1142. this.y = y;
  1143. this.z = z;
  1144. }
  1145. /**
  1146. * Returns a string with the Vector3 coordinates.
  1147. */
  1148. Vector3.prototype.toString = function () {
  1149. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1150. };
  1151. /**
  1152. * Returns the string "Vector3"
  1153. */
  1154. Vector3.prototype.getClassName = function () {
  1155. return "Vector3";
  1156. };
  1157. /**
  1158. * Returns the Vector hash code.
  1159. */
  1160. Vector3.prototype.getHashCode = function () {
  1161. var hash = this.x || 0;
  1162. hash = (hash * 397) ^ (this.y || 0);
  1163. hash = (hash * 397) ^ (this.z || 0);
  1164. return hash;
  1165. };
  1166. // Operators
  1167. /**
  1168. * Returns a new array with three elements : the coordinates the Vector3.
  1169. */
  1170. Vector3.prototype.asArray = function () {
  1171. var result = [];
  1172. this.toArray(result, 0);
  1173. return result;
  1174. };
  1175. /**
  1176. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1177. * Returns the Vector3.
  1178. */
  1179. Vector3.prototype.toArray = function (array, index) {
  1180. if (index === void 0) { index = 0; }
  1181. array[index] = this.x;
  1182. array[index + 1] = this.y;
  1183. array[index + 2] = this.z;
  1184. return this;
  1185. };
  1186. /**
  1187. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1188. */
  1189. Vector3.prototype.toQuaternion = function () {
  1190. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1191. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1192. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1193. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1194. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1195. var cosy = Math.cos(this.y * 0.5);
  1196. var siny = Math.sin(this.y * 0.5);
  1197. result.x = coszMinusx * siny;
  1198. result.y = -sinzMinusx * siny;
  1199. result.z = sinxPlusz * cosy;
  1200. result.w = cosxPlusz * cosy;
  1201. return result;
  1202. };
  1203. /**
  1204. * Adds the passed vector to the current Vector3.
  1205. * Returns the updated Vector3.
  1206. */
  1207. Vector3.prototype.addInPlace = function (otherVector) {
  1208. this.x += otherVector.x;
  1209. this.y += otherVector.y;
  1210. this.z += otherVector.z;
  1211. return this;
  1212. };
  1213. /**
  1214. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1215. */
  1216. Vector3.prototype.add = function (otherVector) {
  1217. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1218. };
  1219. /**
  1220. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1221. * Returns the current Vector3.
  1222. */
  1223. Vector3.prototype.addToRef = function (otherVector, result) {
  1224. result.x = this.x + otherVector.x;
  1225. result.y = this.y + otherVector.y;
  1226. result.z = this.z + otherVector.z;
  1227. return this;
  1228. };
  1229. /**
  1230. * Subtract the passed vector from the current Vector3.
  1231. * Returns the updated Vector3.
  1232. */
  1233. Vector3.prototype.subtractInPlace = function (otherVector) {
  1234. this.x -= otherVector.x;
  1235. this.y -= otherVector.y;
  1236. this.z -= otherVector.z;
  1237. return this;
  1238. };
  1239. /**
  1240. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1241. */
  1242. Vector3.prototype.subtract = function (otherVector) {
  1243. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1244. };
  1245. /**
  1246. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1247. * Returns the current Vector3.
  1248. */
  1249. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1250. result.x = this.x - otherVector.x;
  1251. result.y = this.y - otherVector.y;
  1252. result.z = this.z - otherVector.z;
  1253. return this;
  1254. };
  1255. /**
  1256. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1257. */
  1258. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1259. return new Vector3(this.x - x, this.y - y, this.z - z);
  1260. };
  1261. /**
  1262. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1263. * Returns the current Vector3.
  1264. */
  1265. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1266. result.x = this.x - x;
  1267. result.y = this.y - y;
  1268. result.z = this.z - z;
  1269. return this;
  1270. };
  1271. /**
  1272. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1273. */
  1274. Vector3.prototype.negate = function () {
  1275. return new Vector3(-this.x, -this.y, -this.z);
  1276. };
  1277. /**
  1278. * Multiplies the Vector3 coordinates by the float "scale".
  1279. * Returns the updated Vector3.
  1280. */
  1281. Vector3.prototype.scaleInPlace = function (scale) {
  1282. this.x *= scale;
  1283. this.y *= scale;
  1284. this.z *= scale;
  1285. return this;
  1286. };
  1287. /**
  1288. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1289. */
  1290. Vector3.prototype.scale = function (scale) {
  1291. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1292. };
  1293. /**
  1294. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1295. * Returns the current Vector3.
  1296. */
  1297. Vector3.prototype.scaleToRef = function (scale, result) {
  1298. result.x = this.x * scale;
  1299. result.y = this.y * scale;
  1300. result.z = this.z * scale;
  1301. return this;
  1302. };
  1303. /**
  1304. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1305. */
  1306. Vector3.prototype.equals = function (otherVector) {
  1307. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1308. };
  1309. /**
  1310. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1311. */
  1312. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1313. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1314. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1315. };
  1316. /**
  1317. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1318. */
  1319. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1320. return this.x === x && this.y === y && this.z === z;
  1321. };
  1322. /**
  1323. * Muliplies the current Vector3 coordinates by the passed ones.
  1324. * Returns the updated Vector3.
  1325. */
  1326. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1327. this.x *= otherVector.x;
  1328. this.y *= otherVector.y;
  1329. this.z *= otherVector.z;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1334. */
  1335. Vector3.prototype.multiply = function (otherVector) {
  1336. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1337. };
  1338. /**
  1339. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1340. * Returns the current Vector3.
  1341. */
  1342. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1343. result.x = this.x * otherVector.x;
  1344. result.y = this.y * otherVector.y;
  1345. result.z = this.z * otherVector.z;
  1346. return this;
  1347. };
  1348. /**
  1349. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1350. */
  1351. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1352. return new Vector3(this.x * x, this.y * y, this.z * z);
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1356. */
  1357. Vector3.prototype.divide = function (otherVector) {
  1358. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1359. };
  1360. /**
  1361. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1362. * Returns the current Vector3.
  1363. */
  1364. Vector3.prototype.divideToRef = function (otherVector, result) {
  1365. result.x = this.x / otherVector.x;
  1366. result.y = this.y / otherVector.y;
  1367. result.z = this.z / otherVector.z;
  1368. return this;
  1369. };
  1370. /**
  1371. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1372. * Returns the updated Vector3.
  1373. */
  1374. Vector3.prototype.MinimizeInPlace = function (other) {
  1375. if (other.x < this.x)
  1376. this.x = other.x;
  1377. if (other.y < this.y)
  1378. this.y = other.y;
  1379. if (other.z < this.z)
  1380. this.z = other.z;
  1381. return this;
  1382. };
  1383. /**
  1384. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1385. * Returns the updated Vector3.
  1386. */
  1387. Vector3.prototype.MaximizeInPlace = function (other) {
  1388. if (other.x > this.x)
  1389. this.x = other.x;
  1390. if (other.y > this.y)
  1391. this.y = other.y;
  1392. if (other.z > this.z)
  1393. this.z = other.z;
  1394. return this;
  1395. };
  1396. // Properties
  1397. /**
  1398. * Returns the length of the Vector3 (float).
  1399. */
  1400. Vector3.prototype.length = function () {
  1401. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1402. };
  1403. /**
  1404. * Returns the squared length of the Vector3 (float).
  1405. */
  1406. Vector3.prototype.lengthSquared = function () {
  1407. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1408. };
  1409. // Methods
  1410. /**
  1411. * Normalize the current Vector3.
  1412. * Returns the updated Vector3.
  1413. */
  1414. Vector3.prototype.normalize = function () {
  1415. var len = this.length();
  1416. if (len === 0 || len === 1.0)
  1417. return this;
  1418. var num = 1.0 / len;
  1419. this.x *= num;
  1420. this.y *= num;
  1421. this.z *= num;
  1422. return this;
  1423. };
  1424. /**
  1425. * Returns a new Vector3 copied from the current Vector3.
  1426. */
  1427. Vector3.prototype.clone = function () {
  1428. return new Vector3(this.x, this.y, this.z);
  1429. };
  1430. /**
  1431. * Copies the passed vector coordinates to the current Vector3 ones.
  1432. * Returns the updated Vector3.
  1433. */
  1434. Vector3.prototype.copyFrom = function (source) {
  1435. this.x = source.x;
  1436. this.y = source.y;
  1437. this.z = source.z;
  1438. return this;
  1439. };
  1440. /**
  1441. * Copies the passed floats to the current Vector3 coordinates.
  1442. * Returns the updated Vector3.
  1443. */
  1444. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1445. this.x = x;
  1446. this.y = y;
  1447. this.z = z;
  1448. return this;
  1449. };
  1450. /**
  1451. * Copies the passed floats to the current Vector3 coordinates.
  1452. * Returns the updated Vector3.
  1453. */
  1454. Vector3.prototype.set = function (x, y, z) {
  1455. return this.copyFromFloats(x, y, z);
  1456. };
  1457. // Statics
  1458. /**
  1459. *
  1460. */
  1461. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1462. var d0 = Vector3.Dot(vector0, axis) - size;
  1463. var d1 = Vector3.Dot(vector1, axis) - size;
  1464. var s = d0 / (d0 - d1);
  1465. return s;
  1466. };
  1467. /**
  1468. * Returns a new Vector3 set from the index "offset" of the passed array.
  1469. */
  1470. Vector3.FromArray = function (array, offset) {
  1471. if (!offset) {
  1472. offset = 0;
  1473. }
  1474. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1475. };
  1476. /**
  1477. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1478. * This function is deprecated. Use FromArray instead.
  1479. */
  1480. Vector3.FromFloatArray = function (array, offset) {
  1481. return Vector3.FromArray(array, offset);
  1482. };
  1483. /**
  1484. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1485. */
  1486. Vector3.FromArrayToRef = function (array, offset, result) {
  1487. result.x = array[offset];
  1488. result.y = array[offset + 1];
  1489. result.z = array[offset + 2];
  1490. };
  1491. /**
  1492. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1493. * This function is deprecated. Use FromArrayToRef instead.
  1494. */
  1495. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1496. return Vector3.FromArrayToRef(array, offset, result);
  1497. };
  1498. /**
  1499. * Sets the passed vector "result" with the passed floats.
  1500. */
  1501. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1502. result.x = x;
  1503. result.y = y;
  1504. result.z = z;
  1505. };
  1506. /**
  1507. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1508. */
  1509. Vector3.Zero = function () {
  1510. return new Vector3(0.0, 0.0, 0.0);
  1511. };
  1512. /**
  1513. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1514. */
  1515. Vector3.One = function () {
  1516. return new Vector3(1.0, 1.0, 1.0);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1520. */
  1521. Vector3.Up = function () {
  1522. return new Vector3(0.0, 1.0, 0.0);
  1523. };
  1524. /**
  1525. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1526. */
  1527. Vector3.Forward = function () {
  1528. return new Vector3(0.0, 0.0, 1.0);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1532. */
  1533. Vector3.Right = function () {
  1534. return new Vector3(1.0, 0.0, 0.0);
  1535. };
  1536. /**
  1537. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1538. */
  1539. Vector3.Left = function () {
  1540. return new Vector3(-1.0, 0.0, 0.0);
  1541. };
  1542. /**
  1543. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1544. * This method computes tranformed coordinates only, not transformed direction vectors.
  1545. */
  1546. Vector3.TransformCoordinates = function (vector, transformation) {
  1547. var result = Vector3.Zero();
  1548. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1549. return result;
  1550. };
  1551. /**
  1552. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1553. * This method computes tranformed coordinates only, not transformed direction vectors.
  1554. */
  1555. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1558. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1559. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1560. result.x = x / w;
  1561. result.y = y / w;
  1562. result.z = z / w;
  1563. };
  1564. /**
  1565. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1566. * This method computes tranformed coordinates only, not transformed direction vectors.
  1567. */
  1568. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1569. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1570. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1571. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1572. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1573. result.x = rx / rw;
  1574. result.y = ry / rw;
  1575. result.z = rz / rw;
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1579. * This methods computes transformed normalized direction vectors only.
  1580. */
  1581. Vector3.TransformNormal = function (vector, transformation) {
  1582. var result = Vector3.Zero();
  1583. Vector3.TransformNormalToRef(vector, transformation, result);
  1584. return result;
  1585. };
  1586. /**
  1587. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1588. * This methods computes transformed normalized direction vectors only.
  1589. */
  1590. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1591. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1592. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1593. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1594. result.x = x;
  1595. result.y = y;
  1596. result.z = z;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1600. * This methods computes transformed normalized direction vectors only.
  1601. */
  1602. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1603. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1604. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1605. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1606. };
  1607. /**
  1608. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1609. */
  1610. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1611. var squared = amount * amount;
  1612. var cubed = amount * squared;
  1613. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1614. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1615. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1616. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1617. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1618. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1619. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1620. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1621. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1622. return new Vector3(x, y, z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1626. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1627. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1628. */
  1629. Vector3.Clamp = function (value, min, max) {
  1630. var x = value.x;
  1631. x = (x > max.x) ? max.x : x;
  1632. x = (x < min.x) ? min.x : x;
  1633. var y = value.y;
  1634. y = (y > max.y) ? max.y : y;
  1635. y = (y < min.y) ? min.y : y;
  1636. var z = value.z;
  1637. z = (z > max.z) ? max.z : z;
  1638. z = (z < min.z) ? min.z : z;
  1639. return new Vector3(x, y, z);
  1640. };
  1641. /**
  1642. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1643. */
  1644. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1645. var squared = amount * amount;
  1646. var cubed = amount * squared;
  1647. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1648. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1649. var part3 = (cubed - (2.0 * squared)) + amount;
  1650. var part4 = cubed - squared;
  1651. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1652. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1653. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1654. return new Vector3(x, y, z);
  1655. };
  1656. /**
  1657. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1658. */
  1659. Vector3.Lerp = function (start, end, amount) {
  1660. var result = new Vector3(0, 0, 0);
  1661. Vector3.LerpToRef(start, end, amount, result);
  1662. return result;
  1663. };
  1664. /**
  1665. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1666. */
  1667. Vector3.LerpToRef = function (start, end, amount, result) {
  1668. result.x = start.x + ((end.x - start.x) * amount);
  1669. result.y = start.y + ((end.y - start.y) * amount);
  1670. result.z = start.z + ((end.z - start.z) * amount);
  1671. };
  1672. /**
  1673. * Returns the dot product (float) between the vectors "left" and "right".
  1674. */
  1675. Vector3.Dot = function (left, right) {
  1676. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1677. };
  1678. /**
  1679. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1680. * The cross product is then orthogonal to both "left" and "right".
  1681. */
  1682. Vector3.Cross = function (left, right) {
  1683. var result = Vector3.Zero();
  1684. Vector3.CrossToRef(left, right, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the cross product of "left" and "right".
  1689. * The cross product is then orthogonal to both "left" and "right".
  1690. */
  1691. Vector3.CrossToRef = function (left, right, result) {
  1692. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1693. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1694. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1695. result.copyFrom(MathTmp.Vector3[0]);
  1696. };
  1697. /**
  1698. * Returns a new Vector3 as the normalization of the passed vector.
  1699. */
  1700. Vector3.Normalize = function (vector) {
  1701. var result = Vector3.Zero();
  1702. Vector3.NormalizeToRef(vector, result);
  1703. return result;
  1704. };
  1705. /**
  1706. * Sets the passed vector "result" with the normalization of the passed first vector.
  1707. */
  1708. Vector3.NormalizeToRef = function (vector, result) {
  1709. result.copyFrom(vector);
  1710. result.normalize();
  1711. };
  1712. Vector3.Project = function (vector, world, transform, viewport) {
  1713. var cw = viewport.width;
  1714. var ch = viewport.height;
  1715. var cx = viewport.x;
  1716. var cy = viewport.y;
  1717. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1718. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1719. var matrix = MathTmp.Matrix[0];
  1720. world.multiplyToRef(transform, matrix);
  1721. matrix.multiplyToRef(viewportMatrix, matrix);
  1722. return Vector3.TransformCoordinates(vector, matrix);
  1723. };
  1724. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1725. var matrix = MathTmp.Matrix[0];
  1726. world.multiplyToRef(transform, matrix);
  1727. matrix.invert();
  1728. source.x = source.x / viewportWidth * 2 - 1;
  1729. source.y = -(source.y / viewportHeight * 2 - 1);
  1730. var vector = Vector3.TransformCoordinates(source, matrix);
  1731. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1732. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1733. vector = vector.scale(1.0 / num);
  1734. }
  1735. return vector;
  1736. };
  1737. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1738. var matrix = MathTmp.Matrix[0];
  1739. world.multiplyToRef(view, matrix);
  1740. matrix.multiplyToRef(projection, matrix);
  1741. matrix.invert();
  1742. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1743. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1744. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1745. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1746. vector = vector.scale(1.0 / num);
  1747. }
  1748. return vector;
  1749. };
  1750. Vector3.Minimize = function (left, right) {
  1751. var min = left.clone();
  1752. min.MinimizeInPlace(right);
  1753. return min;
  1754. };
  1755. Vector3.Maximize = function (left, right) {
  1756. var max = left.clone();
  1757. max.MaximizeInPlace(right);
  1758. return max;
  1759. };
  1760. /**
  1761. * Returns the distance (float) between the vectors "value1" and "value2".
  1762. */
  1763. Vector3.Distance = function (value1, value2) {
  1764. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1765. };
  1766. /**
  1767. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1768. */
  1769. Vector3.DistanceSquared = function (value1, value2) {
  1770. var x = value1.x - value2.x;
  1771. var y = value1.y - value2.y;
  1772. var z = value1.z - value2.z;
  1773. return (x * x) + (y * y) + (z * z);
  1774. };
  1775. /**
  1776. * Returns a new Vector3 located at the center between "value1" and "value2".
  1777. */
  1778. Vector3.Center = function (value1, value2) {
  1779. var center = value1.add(value2);
  1780. center.scaleInPlace(0.5);
  1781. return center;
  1782. };
  1783. /**
  1784. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1785. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1786. * to something in order to rotate it from its local system to the given target system.
  1787. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1788. * Returns a new Vector3.
  1789. */
  1790. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1791. var rotation = Vector3.Zero();
  1792. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1793. return rotation;
  1794. };
  1795. /**
  1796. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1797. */
  1798. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1799. var quat = MathTmp.Quaternion[0];
  1800. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1801. quat.toEulerAnglesToRef(ref);
  1802. };
  1803. return Vector3;
  1804. }());
  1805. BABYLON.Vector3 = Vector3;
  1806. //Vector4 class created for EulerAngle class conversion to Quaternion
  1807. var Vector4 = (function () {
  1808. /**
  1809. * Creates a Vector4 object from the passed floats.
  1810. */
  1811. function Vector4(x, y, z, w) {
  1812. this.x = x;
  1813. this.y = y;
  1814. this.z = z;
  1815. this.w = w;
  1816. }
  1817. /**
  1818. * Returns the string with the Vector4 coordinates.
  1819. */
  1820. Vector4.prototype.toString = function () {
  1821. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1822. };
  1823. /**
  1824. * Returns the string "Vector4".
  1825. */
  1826. Vector4.prototype.getClassName = function () {
  1827. return "Vector4";
  1828. };
  1829. /**
  1830. * Returns the Vector4 hash code.
  1831. */
  1832. Vector4.prototype.getHashCode = function () {
  1833. var hash = this.x || 0;
  1834. hash = (hash * 397) ^ (this.y || 0);
  1835. hash = (hash * 397) ^ (this.z || 0);
  1836. hash = (hash * 397) ^ (this.w || 0);
  1837. return hash;
  1838. };
  1839. // Operators
  1840. /**
  1841. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.asArray = function () {
  1844. var result = [];
  1845. this.toArray(result, 0);
  1846. return result;
  1847. };
  1848. /**
  1849. * Populates the passed array from the passed index with the Vector4 coordinates.
  1850. * Returns the Vector4.
  1851. */
  1852. Vector4.prototype.toArray = function (array, index) {
  1853. if (index === undefined) {
  1854. index = 0;
  1855. }
  1856. array[index] = this.x;
  1857. array[index + 1] = this.y;
  1858. array[index + 2] = this.z;
  1859. array[index + 3] = this.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Adds the passed vector to the current Vector4.
  1864. * Returns the updated Vector4.
  1865. */
  1866. Vector4.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. this.z += otherVector.z;
  1870. this.w += otherVector.w;
  1871. return this;
  1872. };
  1873. /**
  1874. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1875. */
  1876. Vector4.prototype.add = function (otherVector) {
  1877. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1878. };
  1879. /**
  1880. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1881. * Returns the current Vector4.
  1882. */
  1883. Vector4.prototype.addToRef = function (otherVector, result) {
  1884. result.x = this.x + otherVector.x;
  1885. result.y = this.y + otherVector.y;
  1886. result.z = this.z + otherVector.z;
  1887. result.w = this.w + otherVector.w;
  1888. return this;
  1889. };
  1890. /**
  1891. * Subtract in place the passed vector from the current Vector4.
  1892. * Returns the updated Vector4.
  1893. */
  1894. Vector4.prototype.subtractInPlace = function (otherVector) {
  1895. this.x -= otherVector.x;
  1896. this.y -= otherVector.y;
  1897. this.z -= otherVector.z;
  1898. this.w -= otherVector.w;
  1899. return this;
  1900. };
  1901. /**
  1902. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1903. */
  1904. Vector4.prototype.subtract = function (otherVector) {
  1905. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1906. };
  1907. /**
  1908. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1909. * Returns the current Vector4.
  1910. */
  1911. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1912. result.x = this.x - otherVector.x;
  1913. result.y = this.y - otherVector.y;
  1914. result.z = this.z - otherVector.z;
  1915. result.w = this.w - otherVector.w;
  1916. return this;
  1917. };
  1918. /**
  1919. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1922. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1923. };
  1924. /**
  1925. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1926. * Returns the current Vector4.
  1927. */
  1928. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1929. result.x = this.x - x;
  1930. result.y = this.y - y;
  1931. result.z = this.z - z;
  1932. result.w = this.w - w;
  1933. return this;
  1934. };
  1935. /**
  1936. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1937. */
  1938. Vector4.prototype.negate = function () {
  1939. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1940. };
  1941. /**
  1942. * Multiplies the current Vector4 coordinates by scale (float).
  1943. * Returns the updated Vector4.
  1944. */
  1945. Vector4.prototype.scaleInPlace = function (scale) {
  1946. this.x *= scale;
  1947. this.y *= scale;
  1948. this.z *= scale;
  1949. this.w *= scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1954. */
  1955. Vector4.prototype.scale = function (scale) {
  1956. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1957. };
  1958. /**
  1959. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1960. * Returns the current Vector4.
  1961. */
  1962. Vector4.prototype.scaleToRef = function (scale, result) {
  1963. result.x = this.x * scale;
  1964. result.y = this.y * scale;
  1965. result.z = this.z * scale;
  1966. result.w = this.w * scale;
  1967. return this;
  1968. };
  1969. /**
  1970. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1971. */
  1972. Vector4.prototype.equals = function (otherVector) {
  1973. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1974. };
  1975. /**
  1976. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1977. */
  1978. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1979. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1980. return otherVector
  1981. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1982. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1983. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1984. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1985. };
  1986. /**
  1987. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1988. */
  1989. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1990. return this.x === x && this.y === y && this.z === z && this.w === w;
  1991. };
  1992. /**
  1993. * Multiplies in place the current Vector4 by the passed one.
  1994. * Returns the updated Vector4.
  1995. */
  1996. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1997. this.x *= otherVector.x;
  1998. this.y *= otherVector.y;
  1999. this.z *= otherVector.z;
  2000. this.w *= otherVector.w;
  2001. return this;
  2002. };
  2003. /**
  2004. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2005. */
  2006. Vector4.prototype.multiply = function (otherVector) {
  2007. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2011. * Returns the current Vector4.
  2012. */
  2013. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2014. result.x = this.x * otherVector.x;
  2015. result.y = this.y * otherVector.y;
  2016. result.z = this.z * otherVector.z;
  2017. result.w = this.w * otherVector.w;
  2018. return this;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2022. */
  2023. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2024. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2028. */
  2029. Vector4.prototype.divide = function (otherVector) {
  2030. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.divideToRef = function (otherVector, result) {
  2037. result.x = this.x / otherVector.x;
  2038. result.y = this.y / otherVector.y;
  2039. result.z = this.z / otherVector.z;
  2040. result.w = this.w / otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2045. */
  2046. Vector4.prototype.MinimizeInPlace = function (other) {
  2047. if (other.x < this.x)
  2048. this.x = other.x;
  2049. if (other.y < this.y)
  2050. this.y = other.y;
  2051. if (other.z < this.z)
  2052. this.z = other.z;
  2053. if (other.w < this.w)
  2054. this.w = other.w;
  2055. return this;
  2056. };
  2057. /**
  2058. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2059. */
  2060. Vector4.prototype.MaximizeInPlace = function (other) {
  2061. if (other.x > this.x)
  2062. this.x = other.x;
  2063. if (other.y > this.y)
  2064. this.y = other.y;
  2065. if (other.z > this.z)
  2066. this.z = other.z;
  2067. if (other.w > this.w)
  2068. this.w = other.w;
  2069. return this;
  2070. };
  2071. // Properties
  2072. /**
  2073. * Returns the Vector4 length (float).
  2074. */
  2075. Vector4.prototype.length = function () {
  2076. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2077. };
  2078. /**
  2079. * Returns the Vector4 squared length (float).
  2080. */
  2081. Vector4.prototype.lengthSquared = function () {
  2082. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2083. };
  2084. // Methods
  2085. /**
  2086. * Normalizes in place the Vector4.
  2087. * Returns the updated Vector4.
  2088. */
  2089. Vector4.prototype.normalize = function () {
  2090. var len = this.length();
  2091. if (len === 0)
  2092. return this;
  2093. var num = 1.0 / len;
  2094. this.x *= num;
  2095. this.y *= num;
  2096. this.z *= num;
  2097. this.w *= num;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2102. */
  2103. Vector4.prototype.toVector3 = function () {
  2104. return new Vector3(this.x, this.y, this.z);
  2105. };
  2106. /**
  2107. * Returns a new Vector4 copied from the current one.
  2108. */
  2109. Vector4.prototype.clone = function () {
  2110. return new Vector4(this.x, this.y, this.z, this.w);
  2111. };
  2112. /**
  2113. * Updates the current Vector4 with the passed one coordinates.
  2114. * Returns the updated Vector4.
  2115. */
  2116. Vector4.prototype.copyFrom = function (source) {
  2117. this.x = source.x;
  2118. this.y = source.y;
  2119. this.z = source.z;
  2120. this.w = source.w;
  2121. return this;
  2122. };
  2123. /**
  2124. * Updates the current Vector4 coordinates with the passed floats.
  2125. * Returns the updated Vector4.
  2126. */
  2127. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2128. this.x = x;
  2129. this.y = y;
  2130. this.z = z;
  2131. this.w = w;
  2132. return this;
  2133. };
  2134. /**
  2135. * Updates the current Vector4 coordinates with the passed floats.
  2136. * Returns the updated Vector4.
  2137. */
  2138. Vector4.prototype.set = function (x, y, z, w) {
  2139. return this.copyFromFloats(x, y, z, w);
  2140. };
  2141. // Statics
  2142. /**
  2143. * Returns a new Vector4 set from the starting index of the passed array.
  2144. */
  2145. Vector4.FromArray = function (array, offset) {
  2146. if (!offset) {
  2147. offset = 0;
  2148. }
  2149. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2150. };
  2151. /**
  2152. * Updates the passed vector "result" from the starting index of the passed array.
  2153. */
  2154. Vector4.FromArrayToRef = function (array, offset, result) {
  2155. result.x = array[offset];
  2156. result.y = array[offset + 1];
  2157. result.z = array[offset + 2];
  2158. result.w = array[offset + 3];
  2159. };
  2160. /**
  2161. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2162. */
  2163. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2164. Vector4.FromArrayToRef(array, offset, result);
  2165. };
  2166. /**
  2167. * Updates the passed vector "result" coordinates from the passed floats.
  2168. */
  2169. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2170. result.x = x;
  2171. result.y = y;
  2172. result.z = z;
  2173. result.w = w;
  2174. };
  2175. /**
  2176. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2177. */
  2178. Vector4.Zero = function () {
  2179. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2180. };
  2181. /**
  2182. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2183. */
  2184. Vector4.One = function () {
  2185. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2186. };
  2187. /**
  2188. * Returns a new normalized Vector4 from the passed one.
  2189. */
  2190. Vector4.Normalize = function (vector) {
  2191. var result = Vector4.Zero();
  2192. Vector4.NormalizeToRef(vector, result);
  2193. return result;
  2194. };
  2195. /**
  2196. * Updates the passed vector "result" from the normalization of the passed one.
  2197. */
  2198. Vector4.NormalizeToRef = function (vector, result) {
  2199. result.copyFrom(vector);
  2200. result.normalize();
  2201. };
  2202. Vector4.Minimize = function (left, right) {
  2203. var min = left.clone();
  2204. min.MinimizeInPlace(right);
  2205. return min;
  2206. };
  2207. Vector4.Maximize = function (left, right) {
  2208. var max = left.clone();
  2209. max.MaximizeInPlace(right);
  2210. return max;
  2211. };
  2212. /**
  2213. * Returns the distance (float) between the vectors "value1" and "value2".
  2214. */
  2215. Vector4.Distance = function (value1, value2) {
  2216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2217. };
  2218. /**
  2219. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2220. */
  2221. Vector4.DistanceSquared = function (value1, value2) {
  2222. var x = value1.x - value2.x;
  2223. var y = value1.y - value2.y;
  2224. var z = value1.z - value2.z;
  2225. var w = value1.w - value2.w;
  2226. return (x * x) + (y * y) + (z * z) + (w * w);
  2227. };
  2228. /**
  2229. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2230. */
  2231. Vector4.Center = function (value1, value2) {
  2232. var center = value1.add(value2);
  2233. center.scaleInPlace(0.5);
  2234. return center;
  2235. };
  2236. /**
  2237. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2238. * This methods computes transformed normalized direction vectors only.
  2239. */
  2240. Vector4.TransformNormal = function (vector, transformation) {
  2241. var result = Vector4.Zero();
  2242. Vector4.TransformNormalToRef(vector, transformation, result);
  2243. return result;
  2244. };
  2245. /**
  2246. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2247. * This methods computes transformed normalized direction vectors only.
  2248. */
  2249. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2250. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2251. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2252. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2253. result.x = x;
  2254. result.y = y;
  2255. result.z = z;
  2256. result.w = vector.w;
  2257. };
  2258. /**
  2259. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2260. * This methods computes transformed normalized direction vectors only.
  2261. */
  2262. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2263. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2264. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2265. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2266. result.w = w;
  2267. };
  2268. return Vector4;
  2269. }());
  2270. BABYLON.Vector4 = Vector4;
  2271. var Size = (function () {
  2272. /**
  2273. * Creates a Size object from the passed width and height (floats).
  2274. */
  2275. function Size(width, height) {
  2276. this.width = width;
  2277. this.height = height;
  2278. }
  2279. // Returns a string with the Size width and height.
  2280. Size.prototype.toString = function () {
  2281. return "{W: " + this.width + ", H: " + this.height + "}";
  2282. };
  2283. /**
  2284. * Returns the string "Size"
  2285. */
  2286. Size.prototype.getClassName = function () {
  2287. return "Size";
  2288. };
  2289. /**
  2290. * Returns the Size hash code.
  2291. */
  2292. Size.prototype.getHashCode = function () {
  2293. var hash = this.width || 0;
  2294. hash = (hash * 397) ^ (this.height || 0);
  2295. return hash;
  2296. };
  2297. /**
  2298. * Updates the current size from the passed one.
  2299. * Returns the updated Size.
  2300. */
  2301. Size.prototype.copyFrom = function (src) {
  2302. this.width = src.width;
  2303. this.height = src.height;
  2304. };
  2305. /**
  2306. * Updates in place the current Size from the passed floats.
  2307. * Returns the updated Size.
  2308. */
  2309. Size.prototype.copyFromFloats = function (width, height) {
  2310. this.width = width;
  2311. this.height = height;
  2312. return this;
  2313. };
  2314. /**
  2315. * Updates in place the current Size from the passed floats.
  2316. * Returns the updated Size.
  2317. */
  2318. Size.prototype.set = function (width, height) {
  2319. return this.copyFromFloats(width, height);
  2320. };
  2321. /**
  2322. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2323. */
  2324. Size.prototype.multiplyByFloats = function (w, h) {
  2325. return new Size(this.width * w, this.height * h);
  2326. };
  2327. /**
  2328. * Returns a new Size copied from the passed one.
  2329. */
  2330. Size.prototype.clone = function () {
  2331. return new Size(this.width, this.height);
  2332. };
  2333. /**
  2334. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2335. */
  2336. Size.prototype.equals = function (other) {
  2337. if (!other) {
  2338. return false;
  2339. }
  2340. return (this.width === other.width) && (this.height === other.height);
  2341. };
  2342. Object.defineProperty(Size.prototype, "surface", {
  2343. /**
  2344. * Returns the surface of the Size : width * height (float).
  2345. */
  2346. get: function () {
  2347. return this.width * this.height;
  2348. },
  2349. enumerable: true,
  2350. configurable: true
  2351. });
  2352. /**
  2353. * Returns a new Size set to (0.0, 0.0)
  2354. */
  2355. Size.Zero = function () {
  2356. return new Size(0.0, 0.0);
  2357. };
  2358. /**
  2359. * Returns a new Size set as the addition result of the current Size and the passed one.
  2360. */
  2361. Size.prototype.add = function (otherSize) {
  2362. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2363. return r;
  2364. };
  2365. /**
  2366. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2367. */
  2368. Size.prototype.subtract = function (otherSize) {
  2369. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2370. return r;
  2371. };
  2372. /**
  2373. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2374. */
  2375. Size.Lerp = function (start, end, amount) {
  2376. var w = start.width + ((end.width - start.width) * amount);
  2377. var h = start.height + ((end.height - start.height) * amount);
  2378. return new Size(w, h);
  2379. };
  2380. return Size;
  2381. }());
  2382. BABYLON.Size = Size;
  2383. var Quaternion = (function () {
  2384. /**
  2385. * Creates a new Quaternion from the passed floats.
  2386. */
  2387. function Quaternion(x, y, z, w) {
  2388. if (x === void 0) { x = 0.0; }
  2389. if (y === void 0) { y = 0.0; }
  2390. if (z === void 0) { z = 0.0; }
  2391. if (w === void 0) { w = 1.0; }
  2392. this.x = x;
  2393. this.y = y;
  2394. this.z = z;
  2395. this.w = w;
  2396. }
  2397. /**
  2398. * Returns a string with the Quaternion coordinates.
  2399. */
  2400. Quaternion.prototype.toString = function () {
  2401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2402. };
  2403. /**
  2404. * Returns the string "Quaternion".
  2405. */
  2406. Quaternion.prototype.getClassName = function () {
  2407. return "Quaternion";
  2408. };
  2409. /**
  2410. * Returns the Quaternion hash code.
  2411. */
  2412. Quaternion.prototype.getHashCode = function () {
  2413. var hash = this.x || 0;
  2414. hash = (hash * 397) ^ (this.y || 0);
  2415. hash = (hash * 397) ^ (this.z || 0);
  2416. hash = (hash * 397) ^ (this.w || 0);
  2417. return hash;
  2418. };
  2419. /**
  2420. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2421. */
  2422. Quaternion.prototype.asArray = function () {
  2423. return [this.x, this.y, this.z, this.w];
  2424. };
  2425. /**
  2426. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2427. */
  2428. Quaternion.prototype.equals = function (otherQuaternion) {
  2429. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2430. };
  2431. /**
  2432. * Returns a new Quaternion copied from the current one.
  2433. */
  2434. Quaternion.prototype.clone = function () {
  2435. return new Quaternion(this.x, this.y, this.z, this.w);
  2436. };
  2437. /**
  2438. * Updates the current Quaternion from the passed one coordinates.
  2439. * Returns the updated Quaterion.
  2440. */
  2441. Quaternion.prototype.copyFrom = function (other) {
  2442. this.x = other.x;
  2443. this.y = other.y;
  2444. this.z = other.z;
  2445. this.w = other.w;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Quaternion from the passed float coordinates.
  2450. * Returns the updated Quaterion.
  2451. */
  2452. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2453. this.x = x;
  2454. this.y = y;
  2455. this.z = z;
  2456. this.w = w;
  2457. return this;
  2458. };
  2459. /**
  2460. * Updates the current Quaternion from the passed float coordinates.
  2461. * Returns the updated Quaterion.
  2462. */
  2463. Quaternion.prototype.set = function (x, y, z, w) {
  2464. return this.copyFromFloats(x, y, z, w);
  2465. };
  2466. /**
  2467. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2468. */
  2469. Quaternion.prototype.add = function (other) {
  2470. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2471. };
  2472. /**
  2473. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2474. */
  2475. Quaternion.prototype.subtract = function (other) {
  2476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2477. };
  2478. /**
  2479. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2480. */
  2481. Quaternion.prototype.scale = function (value) {
  2482. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2483. };
  2484. /**
  2485. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2486. */
  2487. Quaternion.prototype.multiply = function (q1) {
  2488. var result = new Quaternion(0, 0, 0, 1.0);
  2489. this.multiplyToRef(q1, result);
  2490. return result;
  2491. };
  2492. /**
  2493. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2494. * Returns the current Quaternion.
  2495. */
  2496. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2497. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2498. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2499. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2500. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2501. result.copyFromFloats(x, y, z, w);
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.multiplyInPlace = function (q1) {
  2509. this.multiplyToRef(q1, this);
  2510. return this;
  2511. };
  2512. /**
  2513. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2514. * Returns the current Quaternion.
  2515. */
  2516. Quaternion.prototype.conjugateToRef = function (ref) {
  2517. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2518. return this;
  2519. };
  2520. /**
  2521. * Conjugates in place the current Quaternion.
  2522. * Returns the updated Quaternion.
  2523. */
  2524. Quaternion.prototype.conjugateInPlace = function () {
  2525. this.x *= -1;
  2526. this.y *= -1;
  2527. this.z *= -1;
  2528. return this;
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2532. */
  2533. Quaternion.prototype.conjugate = function () {
  2534. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2535. return result;
  2536. };
  2537. /**
  2538. * Returns the Quaternion length (float).
  2539. */
  2540. Quaternion.prototype.length = function () {
  2541. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2542. };
  2543. /**
  2544. * Normalize in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.normalize = function () {
  2548. var length = 1.0 / this.length();
  2549. this.x *= length;
  2550. this.y *= length;
  2551. this.z *= length;
  2552. this.w *= length;
  2553. return this;
  2554. };
  2555. /**
  2556. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2557. */
  2558. Quaternion.prototype.toEulerAngles = function (order) {
  2559. if (order === void 0) { order = "YZX"; }
  2560. var result = Vector3.Zero();
  2561. this.toEulerAnglesToRef(result, order);
  2562. return result;
  2563. };
  2564. /**
  2565. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2566. * Returns the current Quaternion.
  2567. */
  2568. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2569. if (order === void 0) { order = "YZX"; }
  2570. var qz = this.z;
  2571. var qx = this.x;
  2572. var qy = this.y;
  2573. var qw = this.w;
  2574. var sqw = qw * qw;
  2575. var sqz = qz * qz;
  2576. var sqx = qx * qx;
  2577. var sqy = qy * qy;
  2578. var zAxisY = qy * qz - qx * qw;
  2579. var limit = .4999999;
  2580. if (zAxisY < -limit) {
  2581. result.y = 2 * Math.atan2(qy, qw);
  2582. result.x = Math.PI / 2;
  2583. result.z = 0;
  2584. }
  2585. else if (zAxisY > limit) {
  2586. result.y = 2 * Math.atan2(qy, qw);
  2587. result.x = -Math.PI / 2;
  2588. result.z = 0;
  2589. }
  2590. else {
  2591. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2592. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2593. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2594. }
  2595. return this;
  2596. };
  2597. /**
  2598. * Updates the passed rotation matrix with the current Quaternion values.
  2599. * Returns the current Quaternion.
  2600. */
  2601. Quaternion.prototype.toRotationMatrix = function (result) {
  2602. var xx = this.x * this.x;
  2603. var yy = this.y * this.y;
  2604. var zz = this.z * this.z;
  2605. var xy = this.x * this.y;
  2606. var zw = this.z * this.w;
  2607. var zx = this.z * this.x;
  2608. var yw = this.y * this.w;
  2609. var yz = this.y * this.z;
  2610. var xw = this.x * this.w;
  2611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2612. result.m[1] = 2.0 * (xy + zw);
  2613. result.m[2] = 2.0 * (zx - yw);
  2614. result.m[3] = 0;
  2615. result.m[4] = 2.0 * (xy - zw);
  2616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2617. result.m[6] = 2.0 * (yz + xw);
  2618. result.m[7] = 0;
  2619. result.m[8] = 2.0 * (zx + yw);
  2620. result.m[9] = 2.0 * (yz - xw);
  2621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2622. result.m[11] = 0;
  2623. result.m[12] = 0;
  2624. result.m[13] = 0;
  2625. result.m[14] = 0;
  2626. result.m[15] = 1.0;
  2627. result._markAsUpdated();
  2628. return this;
  2629. };
  2630. /**
  2631. * Updates the current Quaternion from the passed rotation matrix values.
  2632. * Returns the updated Quaternion.
  2633. */
  2634. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2635. Quaternion.FromRotationMatrixToRef(matrix, this);
  2636. return this;
  2637. };
  2638. // Statics
  2639. /**
  2640. * Returns a new Quaternion set from the passed rotation matrix values.
  2641. */
  2642. Quaternion.FromRotationMatrix = function (matrix) {
  2643. var result = new Quaternion();
  2644. Quaternion.FromRotationMatrixToRef(matrix, result);
  2645. return result;
  2646. };
  2647. /**
  2648. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2649. */
  2650. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2651. var data = matrix.m;
  2652. var m11 = data[0], m12 = data[4], m13 = data[8];
  2653. var m21 = data[1], m22 = data[5], m23 = data[9];
  2654. var m31 = data[2], m32 = data[6], m33 = data[10];
  2655. var trace = m11 + m22 + m33;
  2656. var s;
  2657. if (trace > 0) {
  2658. s = 0.5 / Math.sqrt(trace + 1.0);
  2659. result.w = 0.25 / s;
  2660. result.x = (m32 - m23) * s;
  2661. result.y = (m13 - m31) * s;
  2662. result.z = (m21 - m12) * s;
  2663. }
  2664. else if (m11 > m22 && m11 > m33) {
  2665. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2666. result.w = (m32 - m23) / s;
  2667. result.x = 0.25 * s;
  2668. result.y = (m12 + m21) / s;
  2669. result.z = (m13 + m31) / s;
  2670. }
  2671. else if (m22 > m33) {
  2672. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2673. result.w = (m13 - m31) / s;
  2674. result.x = (m12 + m21) / s;
  2675. result.y = 0.25 * s;
  2676. result.z = (m23 + m32) / s;
  2677. }
  2678. else {
  2679. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2680. result.w = (m21 - m12) / s;
  2681. result.x = (m13 + m31) / s;
  2682. result.y = (m23 + m32) / s;
  2683. result.z = 0.25 * s;
  2684. }
  2685. };
  2686. /**
  2687. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2688. */
  2689. Quaternion.Zero = function () {
  2690. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2691. };
  2692. /**
  2693. * Returns a new Quaternion as the inverted current Quaternion.
  2694. */
  2695. Quaternion.Inverse = function (q) {
  2696. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2697. };
  2698. /**
  2699. * Returns the identity Quaternion.
  2700. */
  2701. Quaternion.Identity = function () {
  2702. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2703. };
  2704. Quaternion.IsIdentity = function (quaternion) {
  2705. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2706. };
  2707. /**
  2708. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2709. */
  2710. Quaternion.RotationAxis = function (axis, angle) {
  2711. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2712. };
  2713. /**
  2714. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2715. */
  2716. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2717. var sin = Math.sin(angle / 2);
  2718. axis.normalize();
  2719. result.w = Math.cos(angle / 2);
  2720. result.x = axis.x * sin;
  2721. result.y = axis.y * sin;
  2722. result.z = axis.z * sin;
  2723. return result;
  2724. };
  2725. /**
  2726. * Retuns a new Quaternion set from the starting index of the passed array.
  2727. */
  2728. Quaternion.FromArray = function (array, offset) {
  2729. if (!offset) {
  2730. offset = 0;
  2731. }
  2732. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2733. };
  2734. /**
  2735. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2736. */
  2737. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2738. var q = new Quaternion();
  2739. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2740. return q;
  2741. };
  2742. /**
  2743. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2744. */
  2745. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2746. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2747. var halfRoll = roll * 0.5;
  2748. var halfPitch = pitch * 0.5;
  2749. var halfYaw = yaw * 0.5;
  2750. var sinRoll = Math.sin(halfRoll);
  2751. var cosRoll = Math.cos(halfRoll);
  2752. var sinPitch = Math.sin(halfPitch);
  2753. var cosPitch = Math.cos(halfPitch);
  2754. var sinYaw = Math.sin(halfYaw);
  2755. var cosYaw = Math.cos(halfYaw);
  2756. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2757. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2758. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2759. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2760. };
  2761. /**
  2762. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2763. */
  2764. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2765. var result = new Quaternion();
  2766. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2767. return result;
  2768. };
  2769. /**
  2770. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2771. */
  2772. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2773. // Produces a quaternion from Euler angles in the z-x-z orientation
  2774. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2775. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2776. var halfBeta = beta * 0.5;
  2777. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2778. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2779. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2780. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2781. };
  2782. /**
  2783. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2784. * cf to Vector3.RotationFromAxis() documentation.
  2785. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2786. */
  2787. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2788. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2789. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2790. return quat;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2794. * cf to Vector3.RotationFromAxis() documentation.
  2795. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2796. */
  2797. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2798. var rotMat = MathTmp.Matrix[0];
  2799. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2800. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2801. };
  2802. Quaternion.Slerp = function (left, right, amount) {
  2803. var result = Quaternion.Identity();
  2804. Quaternion.SlerpToRef(left, right, amount, result);
  2805. return result;
  2806. };
  2807. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2808. var num2;
  2809. var num3;
  2810. var num = amount;
  2811. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2812. var flag = false;
  2813. if (num4 < 0) {
  2814. flag = true;
  2815. num4 = -num4;
  2816. }
  2817. if (num4 > 0.999999) {
  2818. num3 = 1 - num;
  2819. num2 = flag ? -num : num;
  2820. }
  2821. else {
  2822. var num5 = Math.acos(num4);
  2823. var num6 = (1.0 / Math.sin(num5));
  2824. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2825. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2826. }
  2827. result.x = (num3 * left.x) + (num2 * right.x);
  2828. result.y = (num3 * left.y) + (num2 * right.y);
  2829. result.z = (num3 * left.z) + (num2 * right.z);
  2830. result.w = (num3 * left.w) + (num2 * right.w);
  2831. };
  2832. /**
  2833. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2834. */
  2835. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2836. var squared = amount * amount;
  2837. var cubed = amount * squared;
  2838. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2839. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2840. var part3 = (cubed - (2.0 * squared)) + amount;
  2841. var part4 = cubed - squared;
  2842. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2843. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2844. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2845. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2846. return new Quaternion(x, y, z, w);
  2847. };
  2848. return Quaternion;
  2849. }());
  2850. BABYLON.Quaternion = Quaternion;
  2851. var Matrix = (function () {
  2852. function Matrix() {
  2853. this._isIdentity = false;
  2854. this._isIdentityDirty = true;
  2855. this.m = new Float32Array(16);
  2856. this._markAsUpdated();
  2857. }
  2858. Matrix.prototype._markAsUpdated = function () {
  2859. this.updateFlag = Matrix._updateFlagSeed++;
  2860. this._isIdentityDirty = true;
  2861. };
  2862. // Properties
  2863. /**
  2864. * Boolean : True is the matrix is the identity matrix
  2865. */
  2866. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2867. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2868. if (this._isIdentityDirty) {
  2869. this._isIdentityDirty = false;
  2870. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2871. this._isIdentity = false;
  2872. }
  2873. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2874. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2875. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2876. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2877. this._isIdentity = false;
  2878. }
  2879. else {
  2880. this._isIdentity = true;
  2881. }
  2882. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2883. this._isIdentity = false;
  2884. }
  2885. }
  2886. return this._isIdentity;
  2887. };
  2888. /**
  2889. * Returns the matrix determinant (float).
  2890. */
  2891. Matrix.prototype.determinant = function () {
  2892. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2893. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2894. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2895. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2896. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2897. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2898. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2899. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2900. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2901. };
  2902. // Methods
  2903. /**
  2904. * Returns the matrix underlying array.
  2905. */
  2906. Matrix.prototype.toArray = function () {
  2907. return this.m;
  2908. };
  2909. /**
  2910. * Returns the matrix underlying array.
  2911. */
  2912. Matrix.prototype.asArray = function () {
  2913. return this.toArray();
  2914. };
  2915. /**
  2916. * Inverts in place the Matrix.
  2917. * Returns the Matrix inverted.
  2918. */
  2919. Matrix.prototype.invert = function () {
  2920. this.invertToRef(this);
  2921. return this;
  2922. };
  2923. /**
  2924. * Sets all the matrix elements to zero.
  2925. * Returns the Matrix.
  2926. */
  2927. Matrix.prototype.reset = function () {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = 0.0;
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2936. */
  2937. Matrix.prototype.add = function (other) {
  2938. var result = new Matrix();
  2939. this.addToRef(other, result);
  2940. return result;
  2941. };
  2942. /**
  2943. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.addToRef = function (other, result) {
  2947. for (var index = 0; index < 16; index++) {
  2948. result.m[index] = this.m[index] + other.m[index];
  2949. }
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Adds in place the passed matrix to the current Matrix.
  2955. * Returns the updated Matrix.
  2956. */
  2957. Matrix.prototype.addToSelf = function (other) {
  2958. for (var index = 0; index < 16; index++) {
  2959. this.m[index] += other.m[index];
  2960. }
  2961. this._markAsUpdated();
  2962. return this;
  2963. };
  2964. /**
  2965. * Sets the passed matrix with the current inverted Matrix.
  2966. * Returns the unmodified current Matrix.
  2967. */
  2968. Matrix.prototype.invertToRef = function (other) {
  2969. var l1 = this.m[0];
  2970. var l2 = this.m[1];
  2971. var l3 = this.m[2];
  2972. var l4 = this.m[3];
  2973. var l5 = this.m[4];
  2974. var l6 = this.m[5];
  2975. var l7 = this.m[6];
  2976. var l8 = this.m[7];
  2977. var l9 = this.m[8];
  2978. var l10 = this.m[9];
  2979. var l11 = this.m[10];
  2980. var l12 = this.m[11];
  2981. var l13 = this.m[12];
  2982. var l14 = this.m[13];
  2983. var l15 = this.m[14];
  2984. var l16 = this.m[15];
  2985. var l17 = (l11 * l16) - (l12 * l15);
  2986. var l18 = (l10 * l16) - (l12 * l14);
  2987. var l19 = (l10 * l15) - (l11 * l14);
  2988. var l20 = (l9 * l16) - (l12 * l13);
  2989. var l21 = (l9 * l15) - (l11 * l13);
  2990. var l22 = (l9 * l14) - (l10 * l13);
  2991. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2992. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2993. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2994. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2995. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2996. var l28 = (l7 * l16) - (l8 * l15);
  2997. var l29 = (l6 * l16) - (l8 * l14);
  2998. var l30 = (l6 * l15) - (l7 * l14);
  2999. var l31 = (l5 * l16) - (l8 * l13);
  3000. var l32 = (l5 * l15) - (l7 * l13);
  3001. var l33 = (l5 * l14) - (l6 * l13);
  3002. var l34 = (l7 * l12) - (l8 * l11);
  3003. var l35 = (l6 * l12) - (l8 * l10);
  3004. var l36 = (l6 * l11) - (l7 * l10);
  3005. var l37 = (l5 * l12) - (l8 * l9);
  3006. var l38 = (l5 * l11) - (l7 * l9);
  3007. var l39 = (l5 * l10) - (l6 * l9);
  3008. other.m[0] = l23 * l27;
  3009. other.m[4] = l24 * l27;
  3010. other.m[8] = l25 * l27;
  3011. other.m[12] = l26 * l27;
  3012. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3013. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3014. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3015. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3016. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3017. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3018. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3019. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3020. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3021. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3022. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3023. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3024. other._markAsUpdated();
  3025. return this;
  3026. };
  3027. /**
  3028. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3029. * Returns the updated Matrix.
  3030. */
  3031. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3032. this.m[12] = x;
  3033. this.m[13] = y;
  3034. this.m[14] = z;
  3035. this._markAsUpdated();
  3036. return this;
  3037. };
  3038. /**
  3039. * Inserts the translation vector in the current Matrix.
  3040. * Returns the updated Matrix.
  3041. */
  3042. Matrix.prototype.setTranslation = function (vector3) {
  3043. this.m[12] = vector3.x;
  3044. this.m[13] = vector3.y;
  3045. this.m[14] = vector3.z;
  3046. this._markAsUpdated();
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns a new Vector3 as the extracted translation from the Matrix.
  3051. */
  3052. Matrix.prototype.getTranslation = function () {
  3053. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3054. };
  3055. /**
  3056. * Fill a Vector3 with the extracted translation from the Matrix.
  3057. */
  3058. Matrix.prototype.getTranslationToRef = function (result) {
  3059. result.x = this.m[12];
  3060. result.y = this.m[13];
  3061. result.z = this.m[14];
  3062. return this;
  3063. };
  3064. /**
  3065. * Remove rotation and scaling part from the Matrix.
  3066. * Returns the updated Matrix.
  3067. */
  3068. Matrix.prototype.removeRotationAndScaling = function () {
  3069. this.setRowFromFloats(0, 1, 0, 0, 0);
  3070. this.setRowFromFloats(1, 0, 1, 0, 0);
  3071. this.setRowFromFloats(2, 0, 0, 1, 0);
  3072. return this;
  3073. };
  3074. /**
  3075. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3076. */
  3077. Matrix.prototype.multiply = function (other) {
  3078. var result = new Matrix();
  3079. this.multiplyToRef(other, result);
  3080. return result;
  3081. };
  3082. /**
  3083. * Updates the current Matrix from the passed one values.
  3084. * Returns the updated Matrix.
  3085. */
  3086. Matrix.prototype.copyFrom = function (other) {
  3087. for (var index = 0; index < 16; index++) {
  3088. this.m[index] = other.m[index];
  3089. }
  3090. this._markAsUpdated();
  3091. return this;
  3092. };
  3093. /**
  3094. * Populates the passed array from the starting index with the Matrix values.
  3095. * Returns the Matrix.
  3096. */
  3097. Matrix.prototype.copyToArray = function (array, offset) {
  3098. if (offset === void 0) { offset = 0; }
  3099. for (var index = 0; index < 16; index++) {
  3100. array[offset + index] = this.m[index];
  3101. }
  3102. return this;
  3103. };
  3104. /**
  3105. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3106. */
  3107. Matrix.prototype.multiplyToRef = function (other, result) {
  3108. this.multiplyToArray(other, result.m, 0);
  3109. result._markAsUpdated();
  3110. return this;
  3111. };
  3112. /**
  3113. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3114. */
  3115. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3116. var tm0 = this.m[0];
  3117. var tm1 = this.m[1];
  3118. var tm2 = this.m[2];
  3119. var tm3 = this.m[3];
  3120. var tm4 = this.m[4];
  3121. var tm5 = this.m[5];
  3122. var tm6 = this.m[6];
  3123. var tm7 = this.m[7];
  3124. var tm8 = this.m[8];
  3125. var tm9 = this.m[9];
  3126. var tm10 = this.m[10];
  3127. var tm11 = this.m[11];
  3128. var tm12 = this.m[12];
  3129. var tm13 = this.m[13];
  3130. var tm14 = this.m[14];
  3131. var tm15 = this.m[15];
  3132. var om0 = other.m[0];
  3133. var om1 = other.m[1];
  3134. var om2 = other.m[2];
  3135. var om3 = other.m[3];
  3136. var om4 = other.m[4];
  3137. var om5 = other.m[5];
  3138. var om6 = other.m[6];
  3139. var om7 = other.m[7];
  3140. var om8 = other.m[8];
  3141. var om9 = other.m[9];
  3142. var om10 = other.m[10];
  3143. var om11 = other.m[11];
  3144. var om12 = other.m[12];
  3145. var om13 = other.m[13];
  3146. var om14 = other.m[14];
  3147. var om15 = other.m[15];
  3148. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3149. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3150. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3151. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3152. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3153. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3154. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3155. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3156. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3157. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3158. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3159. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3160. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3161. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3162. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3163. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3164. return this;
  3165. };
  3166. /**
  3167. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3168. */
  3169. Matrix.prototype.equals = function (value) {
  3170. return value &&
  3171. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3172. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3173. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3174. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3175. };
  3176. /**
  3177. * Returns a new Matrix from the current Matrix.
  3178. */
  3179. Matrix.prototype.clone = function () {
  3180. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3181. };
  3182. /**
  3183. * Returns the string "Matrix"
  3184. */
  3185. Matrix.prototype.getClassName = function () {
  3186. return "Matrix";
  3187. };
  3188. /**
  3189. * Returns the Matrix hash code.
  3190. */
  3191. Matrix.prototype.getHashCode = function () {
  3192. var hash = this.m[0] || 0;
  3193. for (var i = 1; i < 16; i++) {
  3194. hash = (hash * 397) ^ (this.m[i] || 0);
  3195. }
  3196. return hash;
  3197. };
  3198. /**
  3199. * Decomposes the current Matrix into :
  3200. * - a scale vector3 passed as a reference to update,
  3201. * - a rotation quaternion passed as a reference to update,
  3202. * - a translation vector3 passed as a reference to update.
  3203. * Returns the boolean `true`.
  3204. */
  3205. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3206. translation.x = this.m[12];
  3207. translation.y = this.m[13];
  3208. translation.z = this.m[14];
  3209. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3210. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3211. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3212. if (this.determinant() <= 0) {
  3213. scale.y *= -1;
  3214. }
  3215. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3216. rotation.x = 0;
  3217. rotation.y = 0;
  3218. rotation.z = 0;
  3219. rotation.w = 1;
  3220. return false;
  3221. }
  3222. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3223. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3224. return true;
  3225. };
  3226. /**
  3227. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3228. */
  3229. Matrix.prototype.getRotationMatrix = function () {
  3230. var result = Matrix.Identity();
  3231. this.getRotationMatrixToRef(result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3236. * Returns the current Matrix.
  3237. */
  3238. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3239. var m = this.m;
  3240. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3241. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3242. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3243. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3244. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3245. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3246. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3247. return this;
  3248. };
  3249. // Statics
  3250. /**
  3251. * Returns a new Matrix set from the starting index of the passed array.
  3252. */
  3253. Matrix.FromArray = function (array, offset) {
  3254. var result = new Matrix();
  3255. if (!offset) {
  3256. offset = 0;
  3257. }
  3258. Matrix.FromArrayToRef(array, offset, result);
  3259. return result;
  3260. };
  3261. /**
  3262. * Sets the passed "result" matrix from the starting index of the passed array.
  3263. */
  3264. Matrix.FromArrayToRef = function (array, offset, result) {
  3265. for (var index = 0; index < 16; index++) {
  3266. result.m[index] = array[index + offset];
  3267. }
  3268. result._markAsUpdated();
  3269. };
  3270. /**
  3271. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3272. */
  3273. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3274. for (var index = 0; index < 16; index++) {
  3275. result.m[index] = array[index + offset] * scale;
  3276. }
  3277. result._markAsUpdated();
  3278. };
  3279. /**
  3280. * Sets the passed matrix "result" with the 16 passed floats.
  3281. */
  3282. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3283. result.m[0] = initialM11;
  3284. result.m[1] = initialM12;
  3285. result.m[2] = initialM13;
  3286. result.m[3] = initialM14;
  3287. result.m[4] = initialM21;
  3288. result.m[5] = initialM22;
  3289. result.m[6] = initialM23;
  3290. result.m[7] = initialM24;
  3291. result.m[8] = initialM31;
  3292. result.m[9] = initialM32;
  3293. result.m[10] = initialM33;
  3294. result.m[11] = initialM34;
  3295. result.m[12] = initialM41;
  3296. result.m[13] = initialM42;
  3297. result.m[14] = initialM43;
  3298. result.m[15] = initialM44;
  3299. result._markAsUpdated();
  3300. };
  3301. /**
  3302. * Returns the index-th row of the current matrix as a new Vector4.
  3303. */
  3304. Matrix.prototype.getRow = function (index) {
  3305. if (index < 0 || index > 3) {
  3306. return null;
  3307. }
  3308. var i = index * 4;
  3309. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3310. };
  3311. /**
  3312. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3313. * Returns the updated Matrix.
  3314. */
  3315. Matrix.prototype.setRow = function (index, row) {
  3316. if (index < 0 || index > 3) {
  3317. return this;
  3318. }
  3319. var i = index * 4;
  3320. this.m[i + 0] = row.x;
  3321. this.m[i + 1] = row.y;
  3322. this.m[i + 2] = row.z;
  3323. this.m[i + 3] = row.w;
  3324. this._markAsUpdated();
  3325. return this;
  3326. };
  3327. /**
  3328. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3329. * Returns the updated Matrix.
  3330. */
  3331. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3332. if (index < 0 || index > 3) {
  3333. return this;
  3334. }
  3335. var i = index * 4;
  3336. this.m[i + 0] = x;
  3337. this.m[i + 1] = y;
  3338. this.m[i + 2] = z;
  3339. this.m[i + 3] = w;
  3340. this._markAsUpdated();
  3341. return this;
  3342. };
  3343. /**
  3344. * Returns a new Matrix set from the 16 passed floats.
  3345. */
  3346. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3347. var result = new Matrix();
  3348. result.m[0] = initialM11;
  3349. result.m[1] = initialM12;
  3350. result.m[2] = initialM13;
  3351. result.m[3] = initialM14;
  3352. result.m[4] = initialM21;
  3353. result.m[5] = initialM22;
  3354. result.m[6] = initialM23;
  3355. result.m[7] = initialM24;
  3356. result.m[8] = initialM31;
  3357. result.m[9] = initialM32;
  3358. result.m[10] = initialM33;
  3359. result.m[11] = initialM34;
  3360. result.m[12] = initialM41;
  3361. result.m[13] = initialM42;
  3362. result.m[14] = initialM43;
  3363. result.m[15] = initialM44;
  3364. return result;
  3365. };
  3366. /**
  3367. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3368. */
  3369. Matrix.Compose = function (scale, rotation, translation) {
  3370. var result = Matrix.Identity();
  3371. Matrix.ComposeToRef(scale, rotation, translation, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3376. */
  3377. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3378. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3379. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3380. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3381. result.setTranslation(translation);
  3382. };
  3383. /**
  3384. * Returns a new indentity Matrix.
  3385. */
  3386. Matrix.Identity = function () {
  3387. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3388. };
  3389. /**
  3390. * Sets the passed "result" as an identity matrix.
  3391. */
  3392. Matrix.IdentityToRef = function (result) {
  3393. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3394. };
  3395. /**
  3396. * Returns a new zero Matrix.
  3397. */
  3398. Matrix.Zero = function () {
  3399. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new rotation matrix for "angle" radians around the X axis.
  3403. */
  3404. Matrix.RotationX = function (angle) {
  3405. var result = new Matrix();
  3406. Matrix.RotationXToRef(angle, result);
  3407. return result;
  3408. };
  3409. /**
  3410. * Returns a new Matrix as the passed inverted one.
  3411. */
  3412. Matrix.Invert = function (source) {
  3413. var result = new Matrix();
  3414. source.invertToRef(result);
  3415. return result;
  3416. };
  3417. /**
  3418. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3419. */
  3420. Matrix.RotationXToRef = function (angle, result) {
  3421. var s = Math.sin(angle);
  3422. var c = Math.cos(angle);
  3423. result.m[0] = 1.0;
  3424. result.m[15] = 1.0;
  3425. result.m[5] = c;
  3426. result.m[10] = c;
  3427. result.m[9] = -s;
  3428. result.m[6] = s;
  3429. result.m[1] = 0.0;
  3430. result.m[2] = 0.0;
  3431. result.m[3] = 0.0;
  3432. result.m[4] = 0.0;
  3433. result.m[7] = 0.0;
  3434. result.m[8] = 0.0;
  3435. result.m[11] = 0.0;
  3436. result.m[12] = 0.0;
  3437. result.m[13] = 0.0;
  3438. result.m[14] = 0.0;
  3439. result._markAsUpdated();
  3440. };
  3441. /**
  3442. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3443. */
  3444. Matrix.RotationY = function (angle) {
  3445. var result = new Matrix();
  3446. Matrix.RotationYToRef(angle, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3451. */
  3452. Matrix.RotationYToRef = function (angle, result) {
  3453. var s = Math.sin(angle);
  3454. var c = Math.cos(angle);
  3455. result.m[5] = 1.0;
  3456. result.m[15] = 1.0;
  3457. result.m[0] = c;
  3458. result.m[2] = -s;
  3459. result.m[8] = s;
  3460. result.m[10] = c;
  3461. result.m[1] = 0.0;
  3462. result.m[3] = 0.0;
  3463. result.m[4] = 0.0;
  3464. result.m[6] = 0.0;
  3465. result.m[7] = 0.0;
  3466. result.m[9] = 0.0;
  3467. result.m[11] = 0.0;
  3468. result.m[12] = 0.0;
  3469. result.m[13] = 0.0;
  3470. result.m[14] = 0.0;
  3471. result._markAsUpdated();
  3472. };
  3473. /**
  3474. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3475. */
  3476. Matrix.RotationZ = function (angle) {
  3477. var result = new Matrix();
  3478. Matrix.RotationZToRef(angle, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3483. */
  3484. Matrix.RotationZToRef = function (angle, result) {
  3485. var s = Math.sin(angle);
  3486. var c = Math.cos(angle);
  3487. result.m[10] = 1.0;
  3488. result.m[15] = 1.0;
  3489. result.m[0] = c;
  3490. result.m[1] = s;
  3491. result.m[4] = -s;
  3492. result.m[5] = c;
  3493. result.m[2] = 0.0;
  3494. result.m[3] = 0.0;
  3495. result.m[6] = 0.0;
  3496. result.m[7] = 0.0;
  3497. result.m[8] = 0.0;
  3498. result.m[9] = 0.0;
  3499. result.m[11] = 0.0;
  3500. result.m[12] = 0.0;
  3501. result.m[13] = 0.0;
  3502. result.m[14] = 0.0;
  3503. result._markAsUpdated();
  3504. };
  3505. /**
  3506. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3507. */
  3508. Matrix.RotationAxis = function (axis, angle) {
  3509. var result = Matrix.Zero();
  3510. Matrix.RotationAxisToRef(axis, angle, result);
  3511. return result;
  3512. };
  3513. /**
  3514. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3515. */
  3516. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3517. var s = Math.sin(-angle);
  3518. var c = Math.cos(-angle);
  3519. var c1 = 1 - c;
  3520. axis.normalize();
  3521. result.m[0] = (axis.x * axis.x) * c1 + c;
  3522. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3523. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3524. result.m[3] = 0.0;
  3525. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3526. result.m[5] = (axis.y * axis.y) * c1 + c;
  3527. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3528. result.m[7] = 0.0;
  3529. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3530. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3531. result.m[10] = (axis.z * axis.z) * c1 + c;
  3532. result.m[11] = 0.0;
  3533. result.m[15] = 1.0;
  3534. result._markAsUpdated();
  3535. };
  3536. /**
  3537. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3538. */
  3539. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3540. var result = new Matrix();
  3541. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3546. */
  3547. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3548. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3549. this._tempQuaternion.toRotationMatrix(result);
  3550. };
  3551. /**
  3552. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3553. */
  3554. Matrix.Scaling = function (x, y, z) {
  3555. var result = Matrix.Zero();
  3556. Matrix.ScalingToRef(x, y, z, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3561. */
  3562. Matrix.ScalingToRef = function (x, y, z, result) {
  3563. result.m[0] = x;
  3564. result.m[1] = 0.0;
  3565. result.m[2] = 0.0;
  3566. result.m[3] = 0.0;
  3567. result.m[4] = 0.0;
  3568. result.m[5] = y;
  3569. result.m[6] = 0.0;
  3570. result.m[7] = 0.0;
  3571. result.m[8] = 0.0;
  3572. result.m[9] = 0.0;
  3573. result.m[10] = z;
  3574. result.m[11] = 0.0;
  3575. result.m[12] = 0.0;
  3576. result.m[13] = 0.0;
  3577. result.m[14] = 0.0;
  3578. result.m[15] = 1.0;
  3579. result._markAsUpdated();
  3580. };
  3581. /**
  3582. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3583. */
  3584. Matrix.Translation = function (x, y, z) {
  3585. var result = Matrix.Identity();
  3586. Matrix.TranslationToRef(x, y, z, result);
  3587. return result;
  3588. };
  3589. /**
  3590. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3591. */
  3592. Matrix.TranslationToRef = function (x, y, z, result) {
  3593. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3594. };
  3595. /**
  3596. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3597. */
  3598. Matrix.Lerp = function (startValue, endValue, gradient) {
  3599. var result = Matrix.Zero();
  3600. for (var index = 0; index < 16; index++) {
  3601. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3602. }
  3603. result._markAsUpdated();
  3604. return result;
  3605. };
  3606. /**
  3607. * Returns a new Matrix whose values are computed by :
  3608. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3609. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3610. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3611. */
  3612. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3613. var startScale = new Vector3(0, 0, 0);
  3614. var startRotation = new Quaternion();
  3615. var startTranslation = new Vector3(0, 0, 0);
  3616. startValue.decompose(startScale, startRotation, startTranslation);
  3617. var endScale = new Vector3(0, 0, 0);
  3618. var endRotation = new Quaternion();
  3619. var endTranslation = new Vector3(0, 0, 0);
  3620. endValue.decompose(endScale, endRotation, endTranslation);
  3621. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3622. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3623. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3624. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3625. };
  3626. /**
  3627. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3628. * This methods works for a Left-Handed system.
  3629. */
  3630. Matrix.LookAtLH = function (eye, target, up) {
  3631. var result = Matrix.Zero();
  3632. Matrix.LookAtLHToRef(eye, target, up, result);
  3633. return result;
  3634. };
  3635. /**
  3636. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3637. * This methods works for a Left-Handed system.
  3638. */
  3639. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3640. // Z axis
  3641. target.subtractToRef(eye, this._zAxis);
  3642. this._zAxis.normalize();
  3643. // X axis
  3644. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3645. if (this._xAxis.lengthSquared() === 0) {
  3646. this._xAxis.x = 1.0;
  3647. }
  3648. else {
  3649. this._xAxis.normalize();
  3650. }
  3651. // Y axis
  3652. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3653. this._yAxis.normalize();
  3654. // Eye angles
  3655. var ex = -Vector3.Dot(this._xAxis, eye);
  3656. var ey = -Vector3.Dot(this._yAxis, eye);
  3657. var ez = -Vector3.Dot(this._zAxis, eye);
  3658. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3659. };
  3660. /**
  3661. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3662. * This methods works for a Right-Handed system.
  3663. */
  3664. Matrix.LookAtRH = function (eye, target, up) {
  3665. var result = Matrix.Zero();
  3666. Matrix.LookAtRHToRef(eye, target, up, result);
  3667. return result;
  3668. };
  3669. /**
  3670. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3671. * This methods works for a Left-Handed system.
  3672. */
  3673. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3674. // Z axis
  3675. eye.subtractToRef(target, this._zAxis);
  3676. this._zAxis.normalize();
  3677. // X axis
  3678. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3679. if (this._xAxis.lengthSquared() === 0) {
  3680. this._xAxis.x = 1.0;
  3681. }
  3682. else {
  3683. this._xAxis.normalize();
  3684. }
  3685. // Y axis
  3686. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3687. this._yAxis.normalize();
  3688. // Eye angles
  3689. var ex = -Vector3.Dot(this._xAxis, eye);
  3690. var ey = -Vector3.Dot(this._yAxis, eye);
  3691. var ez = -Vector3.Dot(this._zAxis, eye);
  3692. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3693. };
  3694. /**
  3695. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3696. */
  3697. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3698. var matrix = Matrix.Zero();
  3699. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3700. return matrix;
  3701. };
  3702. /**
  3703. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3704. */
  3705. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3706. var n = znear;
  3707. var f = zfar;
  3708. var a = 2.0 / width;
  3709. var b = 2.0 / height;
  3710. var c = 2.0 / (f - n);
  3711. var d = -(f + n) / (f - n);
  3712. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3713. };
  3714. /**
  3715. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3716. */
  3717. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3718. var matrix = Matrix.Zero();
  3719. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3720. return matrix;
  3721. };
  3722. /**
  3723. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3724. */
  3725. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3726. var n = znear;
  3727. var f = zfar;
  3728. var a = 2.0 / (right - left);
  3729. var b = 2.0 / (top - bottom);
  3730. var c = 2.0 / (f - n);
  3731. var d = -(f + n) / (f - n);
  3732. var i0 = (left + right) / (left - right);
  3733. var i1 = (top + bottom) / (bottom - top);
  3734. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3735. };
  3736. /**
  3737. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3738. */
  3739. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3740. var matrix = Matrix.Zero();
  3741. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3742. return matrix;
  3743. };
  3744. /**
  3745. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3746. */
  3747. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3748. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3749. result.m[10] *= -1.0;
  3750. };
  3751. /**
  3752. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3753. */
  3754. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3755. var matrix = Matrix.Zero();
  3756. var n = znear;
  3757. var f = zfar;
  3758. var a = 2.0 * n / width;
  3759. var b = 2.0 * n / height;
  3760. var c = (f + n) / (f - n);
  3761. var d = -2.0 * f * n / (f - n);
  3762. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3763. return matrix;
  3764. };
  3765. /**
  3766. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3767. */
  3768. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3769. var matrix = Matrix.Zero();
  3770. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3771. return matrix;
  3772. };
  3773. /**
  3774. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3775. */
  3776. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3778. var n = znear;
  3779. var f = zfar;
  3780. var t = 1.0 / (Math.tan(fov * 0.5));
  3781. var a = isVerticalFovFixed ? (t / aspect) : t;
  3782. var b = isVerticalFovFixed ? t : (t * aspect);
  3783. var c = (f + n) / (f - n);
  3784. var d = -2.0 * f * n / (f - n);
  3785. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3786. };
  3787. /**
  3788. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3789. */
  3790. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3791. var matrix = Matrix.Zero();
  3792. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3793. return matrix;
  3794. };
  3795. /**
  3796. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3797. */
  3798. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3799. //alternatively this could be expressed as:
  3800. // m = PerspectiveFovLHToRef
  3801. // m[10] *= -1.0;
  3802. // m[11] *= -1.0;
  3803. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3804. var n = znear;
  3805. var f = zfar;
  3806. var t = 1.0 / (Math.tan(fov * 0.5));
  3807. var a = isVerticalFovFixed ? (t / aspect) : t;
  3808. var b = isVerticalFovFixed ? t : (t * aspect);
  3809. var c = -(f + n) / (f - n);
  3810. var d = -2 * f * n / (f - n);
  3811. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3812. };
  3813. /**
  3814. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3815. */
  3816. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3817. if (rightHanded === void 0) { rightHanded = false; }
  3818. var rightHandedFactor = rightHanded ? -1 : 1;
  3819. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3820. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3821. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3822. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3823. var xScale = 2.0 / (leftTan + rightTan);
  3824. var yScale = 2.0 / (upTan + downTan);
  3825. result.m[0] = xScale;
  3826. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3827. result.m[5] = yScale;
  3828. result.m[6] = result.m[7] = 0.0;
  3829. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3830. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3831. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3832. result.m[10] = -zfar / (znear - zfar);
  3833. result.m[11] = 1.0 * rightHandedFactor;
  3834. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3835. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3836. // result.m[14] = (znear * zfar) / (znear - zfar);
  3837. result._markAsUpdated();
  3838. };
  3839. /**
  3840. * Returns the final transformation matrix : world * view * projection * viewport
  3841. */
  3842. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3843. var cw = viewport.width;
  3844. var ch = viewport.height;
  3845. var cx = viewport.x;
  3846. var cy = viewport.y;
  3847. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3848. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3849. };
  3850. /**
  3851. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3852. */
  3853. Matrix.GetAsMatrix2x2 = function (matrix) {
  3854. return new Float32Array([
  3855. matrix.m[0], matrix.m[1],
  3856. matrix.m[4], matrix.m[5]
  3857. ]);
  3858. };
  3859. /**
  3860. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3861. */
  3862. Matrix.GetAsMatrix3x3 = function (matrix) {
  3863. return new Float32Array([
  3864. matrix.m[0], matrix.m[1], matrix.m[2],
  3865. matrix.m[4], matrix.m[5], matrix.m[6],
  3866. matrix.m[8], matrix.m[9], matrix.m[10]
  3867. ]);
  3868. };
  3869. /**
  3870. * Compute the transpose of the passed Matrix.
  3871. * Returns a new Matrix.
  3872. */
  3873. Matrix.Transpose = function (matrix) {
  3874. var result = new Matrix();
  3875. result.m[0] = matrix.m[0];
  3876. result.m[1] = matrix.m[4];
  3877. result.m[2] = matrix.m[8];
  3878. result.m[3] = matrix.m[12];
  3879. result.m[4] = matrix.m[1];
  3880. result.m[5] = matrix.m[5];
  3881. result.m[6] = matrix.m[9];
  3882. result.m[7] = matrix.m[13];
  3883. result.m[8] = matrix.m[2];
  3884. result.m[9] = matrix.m[6];
  3885. result.m[10] = matrix.m[10];
  3886. result.m[11] = matrix.m[14];
  3887. result.m[12] = matrix.m[3];
  3888. result.m[13] = matrix.m[7];
  3889. result.m[14] = matrix.m[11];
  3890. result.m[15] = matrix.m[15];
  3891. return result;
  3892. };
  3893. /**
  3894. * Returns a new Matrix as the reflection matrix across the passed plane.
  3895. */
  3896. Matrix.Reflection = function (plane) {
  3897. var matrix = new Matrix();
  3898. Matrix.ReflectionToRef(plane, matrix);
  3899. return matrix;
  3900. };
  3901. /**
  3902. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3903. */
  3904. Matrix.ReflectionToRef = function (plane, result) {
  3905. plane.normalize();
  3906. var x = plane.normal.x;
  3907. var y = plane.normal.y;
  3908. var z = plane.normal.z;
  3909. var temp = -2 * x;
  3910. var temp2 = -2 * y;
  3911. var temp3 = -2 * z;
  3912. result.m[0] = (temp * x) + 1;
  3913. result.m[1] = temp2 * x;
  3914. result.m[2] = temp3 * x;
  3915. result.m[3] = 0.0;
  3916. result.m[4] = temp * y;
  3917. result.m[5] = (temp2 * y) + 1;
  3918. result.m[6] = temp3 * y;
  3919. result.m[7] = 0.0;
  3920. result.m[8] = temp * z;
  3921. result.m[9] = temp2 * z;
  3922. result.m[10] = (temp3 * z) + 1;
  3923. result.m[11] = 0.0;
  3924. result.m[12] = temp * plane.d;
  3925. result.m[13] = temp2 * plane.d;
  3926. result.m[14] = temp3 * plane.d;
  3927. result.m[15] = 1.0;
  3928. result._markAsUpdated();
  3929. };
  3930. /**
  3931. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3932. */
  3933. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3934. result.m[0] = xaxis.x;
  3935. result.m[1] = xaxis.y;
  3936. result.m[2] = xaxis.z;
  3937. result.m[3] = 0.0;
  3938. result.m[4] = yaxis.x;
  3939. result.m[5] = yaxis.y;
  3940. result.m[6] = yaxis.z;
  3941. result.m[7] = 0.0;
  3942. result.m[8] = zaxis.x;
  3943. result.m[9] = zaxis.y;
  3944. result.m[10] = zaxis.z;
  3945. result.m[11] = 0.0;
  3946. result.m[12] = 0.0;
  3947. result.m[13] = 0.0;
  3948. result.m[14] = 0.0;
  3949. result.m[15] = 1.0;
  3950. result._markAsUpdated();
  3951. };
  3952. /**
  3953. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3954. */
  3955. Matrix.FromQuaternionToRef = function (quat, result) {
  3956. var xx = quat.x * quat.x;
  3957. var yy = quat.y * quat.y;
  3958. var zz = quat.z * quat.z;
  3959. var xy = quat.x * quat.y;
  3960. var zw = quat.z * quat.w;
  3961. var zx = quat.z * quat.x;
  3962. var yw = quat.y * quat.w;
  3963. var yz = quat.y * quat.z;
  3964. var xw = quat.x * quat.w;
  3965. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3966. result.m[1] = 2.0 * (xy + zw);
  3967. result.m[2] = 2.0 * (zx - yw);
  3968. result.m[3] = 0.0;
  3969. result.m[4] = 2.0 * (xy - zw);
  3970. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3971. result.m[6] = 2.0 * (yz + xw);
  3972. result.m[7] = 0.0;
  3973. result.m[8] = 2.0 * (zx + yw);
  3974. result.m[9] = 2.0 * (yz - xw);
  3975. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3976. result.m[11] = 0.0;
  3977. result.m[12] = 0.0;
  3978. result.m[13] = 0.0;
  3979. result.m[14] = 0.0;
  3980. result.m[15] = 1.0;
  3981. result._markAsUpdated();
  3982. };
  3983. Matrix._tempQuaternion = new Quaternion();
  3984. Matrix._xAxis = Vector3.Zero();
  3985. Matrix._yAxis = Vector3.Zero();
  3986. Matrix._zAxis = Vector3.Zero();
  3987. Matrix._updateFlagSeed = 0;
  3988. return Matrix;
  3989. }());
  3990. BABYLON.Matrix = Matrix;
  3991. var Plane = (function () {
  3992. /**
  3993. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3994. */
  3995. function Plane(a, b, c, d) {
  3996. this.normal = new Vector3(a, b, c);
  3997. this.d = d;
  3998. }
  3999. /**
  4000. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4001. */
  4002. Plane.prototype.asArray = function () {
  4003. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4004. };
  4005. // Methods
  4006. /**
  4007. * Returns a new plane copied from the current Plane.
  4008. */
  4009. Plane.prototype.clone = function () {
  4010. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4011. };
  4012. /**
  4013. * Returns the string "Plane".
  4014. */
  4015. Plane.prototype.getClassName = function () {
  4016. return "Plane";
  4017. };
  4018. /**
  4019. * Returns the Plane hash code.
  4020. */
  4021. Plane.prototype.getHashCode = function () {
  4022. var hash = this.normal.getHashCode();
  4023. hash = (hash * 397) ^ (this.d || 0);
  4024. return hash;
  4025. };
  4026. /**
  4027. * Normalize the current Plane in place.
  4028. * Returns the updated Plane.
  4029. */
  4030. Plane.prototype.normalize = function () {
  4031. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4032. var magnitude = 0.0;
  4033. if (norm !== 0) {
  4034. magnitude = 1.0 / norm;
  4035. }
  4036. this.normal.x *= magnitude;
  4037. this.normal.y *= magnitude;
  4038. this.normal.z *= magnitude;
  4039. this.d *= magnitude;
  4040. return this;
  4041. };
  4042. /**
  4043. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4044. */
  4045. Plane.prototype.transform = function (transformation) {
  4046. var transposedMatrix = Matrix.Transpose(transformation);
  4047. var x = this.normal.x;
  4048. var y = this.normal.y;
  4049. var z = this.normal.z;
  4050. var d = this.d;
  4051. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4052. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4053. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4054. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4055. return new Plane(normalX, normalY, normalZ, finalD);
  4056. };
  4057. /**
  4058. * Returns the dot product (float) of the point coordinates and the plane normal.
  4059. */
  4060. Plane.prototype.dotCoordinate = function (point) {
  4061. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4062. };
  4063. /**
  4064. * Updates the current Plane from the plane defined by the three passed points.
  4065. * Returns the updated Plane.
  4066. */
  4067. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4068. var x1 = point2.x - point1.x;
  4069. var y1 = point2.y - point1.y;
  4070. var z1 = point2.z - point1.z;
  4071. var x2 = point3.x - point1.x;
  4072. var y2 = point3.y - point1.y;
  4073. var z2 = point3.z - point1.z;
  4074. var yz = (y1 * z2) - (z1 * y2);
  4075. var xz = (z1 * x2) - (x1 * z2);
  4076. var xy = (x1 * y2) - (y1 * x2);
  4077. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4078. var invPyth;
  4079. if (pyth !== 0) {
  4080. invPyth = 1.0 / pyth;
  4081. }
  4082. else {
  4083. invPyth = 0.0;
  4084. }
  4085. this.normal.x = yz * invPyth;
  4086. this.normal.y = xz * invPyth;
  4087. this.normal.z = xy * invPyth;
  4088. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4089. return this;
  4090. };
  4091. /**
  4092. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4093. */
  4094. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4095. var dot = Vector3.Dot(this.normal, direction);
  4096. return (dot <= epsilon);
  4097. };
  4098. /**
  4099. * Returns the signed distance (float) from the passed point to the Plane.
  4100. */
  4101. Plane.prototype.signedDistanceTo = function (point) {
  4102. return Vector3.Dot(point, this.normal) + this.d;
  4103. };
  4104. // Statics
  4105. /**
  4106. * Returns a new Plane from the passed array.
  4107. */
  4108. Plane.FromArray = function (array) {
  4109. return new Plane(array[0], array[1], array[2], array[3]);
  4110. };
  4111. /**
  4112. * Returns a new Plane defined by the three passed points.
  4113. */
  4114. Plane.FromPoints = function (point1, point2, point3) {
  4115. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4116. result.copyFromPoints(point1, point2, point3);
  4117. return result;
  4118. };
  4119. /**
  4120. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4121. * Note : the vector "normal" is updated because normalized.
  4122. */
  4123. Plane.FromPositionAndNormal = function (origin, normal) {
  4124. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4125. normal.normalize();
  4126. result.normal = normal;
  4127. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4128. return result;
  4129. };
  4130. /**
  4131. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4132. */
  4133. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4134. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4135. return Vector3.Dot(point, normal) + d;
  4136. };
  4137. return Plane;
  4138. }());
  4139. BABYLON.Plane = Plane;
  4140. var Viewport = (function () {
  4141. /**
  4142. * Creates a Viewport object located at (x, y) and sized (width, height).
  4143. */
  4144. function Viewport(x, y, width, height) {
  4145. this.x = x;
  4146. this.y = y;
  4147. this.width = width;
  4148. this.height = height;
  4149. }
  4150. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4151. if (renderWidthOrEngine.getRenderWidth) {
  4152. var engine = renderWidthOrEngine;
  4153. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4154. }
  4155. var renderWidth = renderWidthOrEngine;
  4156. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4157. };
  4158. /**
  4159. * Returns a new Viewport copied from the current one.
  4160. */
  4161. Viewport.prototype.clone = function () {
  4162. return new Viewport(this.x, this.y, this.width, this.height);
  4163. };
  4164. return Viewport;
  4165. }());
  4166. BABYLON.Viewport = Viewport;
  4167. var Frustum = (function () {
  4168. function Frustum() {
  4169. }
  4170. /**
  4171. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4172. */
  4173. Frustum.GetPlanes = function (transform) {
  4174. var frustumPlanes = [];
  4175. for (var index = 0; index < 6; index++) {
  4176. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4177. }
  4178. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4179. return frustumPlanes;
  4180. };
  4181. /**
  4182. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4183. */
  4184. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4185. // Near
  4186. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4187. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4188. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4189. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4190. frustumPlanes[0].normalize();
  4191. // Far
  4192. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4193. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4194. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4195. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4196. frustumPlanes[1].normalize();
  4197. // Left
  4198. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4199. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4200. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4201. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4202. frustumPlanes[2].normalize();
  4203. // Right
  4204. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4205. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4206. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4207. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4208. frustumPlanes[3].normalize();
  4209. // Top
  4210. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4211. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4212. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4213. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4214. frustumPlanes[4].normalize();
  4215. // Bottom
  4216. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4217. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4218. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4219. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4220. frustumPlanes[5].normalize();
  4221. };
  4222. return Frustum;
  4223. }());
  4224. BABYLON.Frustum = Frustum;
  4225. var Space;
  4226. (function (Space) {
  4227. Space[Space["LOCAL"] = 0] = "LOCAL";
  4228. Space[Space["WORLD"] = 1] = "WORLD";
  4229. Space[Space["BONE"] = 2] = "BONE";
  4230. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4231. var Axis = (function () {
  4232. function Axis() {
  4233. }
  4234. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4235. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4236. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4237. return Axis;
  4238. }());
  4239. BABYLON.Axis = Axis;
  4240. ;
  4241. var BezierCurve = (function () {
  4242. function BezierCurve() {
  4243. }
  4244. /**
  4245. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4246. */
  4247. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4248. // Extract X (which is equal to time here)
  4249. var f0 = 1 - 3 * x2 + 3 * x1;
  4250. var f1 = 3 * x2 - 6 * x1;
  4251. var f2 = 3 * x1;
  4252. var refinedT = t;
  4253. for (var i = 0; i < 5; i++) {
  4254. var refinedT2 = refinedT * refinedT;
  4255. var refinedT3 = refinedT2 * refinedT;
  4256. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4257. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4258. refinedT -= (x - t) * slope;
  4259. refinedT = Math.min(1, Math.max(0, refinedT));
  4260. }
  4261. // Resolve cubic bezier for the given x
  4262. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4263. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4264. Math.pow(refinedT, 3);
  4265. };
  4266. return BezierCurve;
  4267. }());
  4268. BABYLON.BezierCurve = BezierCurve;
  4269. var Orientation;
  4270. (function (Orientation) {
  4271. Orientation[Orientation["CW"] = 0] = "CW";
  4272. Orientation[Orientation["CCW"] = 1] = "CCW";
  4273. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4274. var Angle = (function () {
  4275. /**
  4276. * Creates an Angle object of "radians" radians (float).
  4277. */
  4278. function Angle(radians) {
  4279. var _this = this;
  4280. /**
  4281. * Returns the Angle value in degrees (float).
  4282. */
  4283. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4284. /**
  4285. * Returns the Angle value in radians (float).
  4286. */
  4287. this.radians = function () { return _this._radians; };
  4288. this._radians = radians;
  4289. if (this._radians < 0.0)
  4290. this._radians += (2.0 * Math.PI);
  4291. }
  4292. /**
  4293. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4294. */
  4295. Angle.BetweenTwoPoints = function (a, b) {
  4296. var delta = b.subtract(a);
  4297. var theta = Math.atan2(delta.y, delta.x);
  4298. return new Angle(theta);
  4299. };
  4300. /**
  4301. * Returns a new Angle object from the passed float in radians.
  4302. */
  4303. Angle.FromRadians = function (radians) {
  4304. return new Angle(radians);
  4305. };
  4306. /**
  4307. * Returns a new Angle object from the passed float in degrees.
  4308. */
  4309. Angle.FromDegrees = function (degrees) {
  4310. return new Angle(degrees * Math.PI / 180.0);
  4311. };
  4312. return Angle;
  4313. }());
  4314. BABYLON.Angle = Angle;
  4315. var Arc2 = (function () {
  4316. /**
  4317. * Creates an Arc object from the three passed points : start, middle and end.
  4318. */
  4319. function Arc2(startPoint, midPoint, endPoint) {
  4320. this.startPoint = startPoint;
  4321. this.midPoint = midPoint;
  4322. this.endPoint = endPoint;
  4323. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4324. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4325. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4326. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4327. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4328. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4329. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4330. var a1 = this.startAngle.degrees();
  4331. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4332. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4333. // angles correction
  4334. if (a2 - a1 > +180.0)
  4335. a2 -= 360.0;
  4336. if (a2 - a1 < -180.0)
  4337. a2 += 360.0;
  4338. if (a3 - a2 > +180.0)
  4339. a3 -= 360.0;
  4340. if (a3 - a2 < -180.0)
  4341. a3 += 360.0;
  4342. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4343. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4344. }
  4345. return Arc2;
  4346. }());
  4347. BABYLON.Arc2 = Arc2;
  4348. var Path2 = (function () {
  4349. /**
  4350. * Creates a Path2 object from the starting 2D coordinates x and y.
  4351. */
  4352. function Path2(x, y) {
  4353. this._points = new Array();
  4354. this._length = 0.0;
  4355. this.closed = false;
  4356. this._points.push(new Vector2(x, y));
  4357. }
  4358. /**
  4359. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4360. * Returns the updated Path2.
  4361. */
  4362. Path2.prototype.addLineTo = function (x, y) {
  4363. if (closed) {
  4364. //Tools.Error("cannot add lines to closed paths");
  4365. return this;
  4366. }
  4367. var newPoint = new Vector2(x, y);
  4368. var previousPoint = this._points[this._points.length - 1];
  4369. this._points.push(newPoint);
  4370. this._length += newPoint.subtract(previousPoint).length();
  4371. return this;
  4372. };
  4373. /**
  4374. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4375. * Returns the updated Path2.
  4376. */
  4377. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4378. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4379. if (closed) {
  4380. //Tools.Error("cannot add arcs to closed paths");
  4381. return this;
  4382. }
  4383. var startPoint = this._points[this._points.length - 1];
  4384. var midPoint = new Vector2(midX, midY);
  4385. var endPoint = new Vector2(endX, endY);
  4386. var arc = new Arc2(startPoint, midPoint, endPoint);
  4387. var increment = arc.angle.radians() / numberOfSegments;
  4388. if (arc.orientation === Orientation.CW)
  4389. increment *= -1;
  4390. var currentAngle = arc.startAngle.radians() + increment;
  4391. for (var i = 0; i < numberOfSegments; i++) {
  4392. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4393. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4394. this.addLineTo(x, y);
  4395. currentAngle += increment;
  4396. }
  4397. return this;
  4398. };
  4399. /**
  4400. * Closes the Path2.
  4401. * Returns the Path2.
  4402. */
  4403. Path2.prototype.close = function () {
  4404. this.closed = true;
  4405. return this;
  4406. };
  4407. /**
  4408. * Returns the Path2 total length (float).
  4409. */
  4410. Path2.prototype.length = function () {
  4411. var result = this._length;
  4412. if (!this.closed) {
  4413. var lastPoint = this._points[this._points.length - 1];
  4414. var firstPoint = this._points[0];
  4415. result += (firstPoint.subtract(lastPoint).length());
  4416. }
  4417. return result;
  4418. };
  4419. /**
  4420. * Returns the Path2 internal array of points.
  4421. */
  4422. Path2.prototype.getPoints = function () {
  4423. return this._points;
  4424. };
  4425. /**
  4426. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4427. */
  4428. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4429. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4430. //Tools.Error("normalized length position should be between 0 and 1.");
  4431. return Vector2.Zero();
  4432. }
  4433. var lengthPosition = normalizedLengthPosition * this.length();
  4434. var previousOffset = 0;
  4435. for (var i = 0; i < this._points.length; i++) {
  4436. var j = (i + 1) % this._points.length;
  4437. var a = this._points[i];
  4438. var b = this._points[j];
  4439. var bToA = b.subtract(a);
  4440. var nextOffset = (bToA.length() + previousOffset);
  4441. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4442. var dir = bToA.normalize();
  4443. var localOffset = lengthPosition - previousOffset;
  4444. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4445. }
  4446. previousOffset = nextOffset;
  4447. }
  4448. //Tools.Error("internal error");
  4449. return Vector2.Zero();
  4450. };
  4451. /**
  4452. * Returns a new Path2 starting at the coordinates (x, y).
  4453. */
  4454. Path2.StartingAt = function (x, y) {
  4455. return new Path2(x, y);
  4456. };
  4457. return Path2;
  4458. }());
  4459. BABYLON.Path2 = Path2;
  4460. var Path3D = (function () {
  4461. /**
  4462. * new Path3D(path, normal, raw)
  4463. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4464. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4465. * path : an array of Vector3, the curve axis of the Path3D
  4466. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4467. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4468. */
  4469. function Path3D(path, firstNormal, raw) {
  4470. this.path = path;
  4471. this._curve = new Array();
  4472. this._distances = new Array();
  4473. this._tangents = new Array();
  4474. this._normals = new Array();
  4475. this._binormals = new Array();
  4476. for (var p = 0; p < path.length; p++) {
  4477. this._curve[p] = path[p].clone(); // hard copy
  4478. }
  4479. this._raw = raw || false;
  4480. this._compute(firstNormal);
  4481. }
  4482. /**
  4483. * Returns the Path3D array of successive Vector3 designing its curve.
  4484. */
  4485. Path3D.prototype.getCurve = function () {
  4486. return this._curve;
  4487. };
  4488. /**
  4489. * Returns an array populated with tangent vectors on each Path3D curve point.
  4490. */
  4491. Path3D.prototype.getTangents = function () {
  4492. return this._tangents;
  4493. };
  4494. /**
  4495. * Returns an array populated with normal vectors on each Path3D curve point.
  4496. */
  4497. Path3D.prototype.getNormals = function () {
  4498. return this._normals;
  4499. };
  4500. /**
  4501. * Returns an array populated with binormal vectors on each Path3D curve point.
  4502. */
  4503. Path3D.prototype.getBinormals = function () {
  4504. return this._binormals;
  4505. };
  4506. /**
  4507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4508. */
  4509. Path3D.prototype.getDistances = function () {
  4510. return this._distances;
  4511. };
  4512. /**
  4513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4514. * Returns the same object updated.
  4515. */
  4516. Path3D.prototype.update = function (path, firstNormal) {
  4517. for (var p = 0; p < path.length; p++) {
  4518. this._curve[p].x = path[p].x;
  4519. this._curve[p].y = path[p].y;
  4520. this._curve[p].z = path[p].z;
  4521. }
  4522. this._compute(firstNormal);
  4523. return this;
  4524. };
  4525. // private function compute() : computes tangents, normals and binormals
  4526. Path3D.prototype._compute = function (firstNormal) {
  4527. var l = this._curve.length;
  4528. // first and last tangents
  4529. this._tangents[0] = this._getFirstNonNullVector(0);
  4530. if (!this._raw) {
  4531. this._tangents[0].normalize();
  4532. }
  4533. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4534. if (!this._raw) {
  4535. this._tangents[l - 1].normalize();
  4536. }
  4537. // normals and binormals at first point : arbitrary vector with _normalVector()
  4538. var tg0 = this._tangents[0];
  4539. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4540. this._normals[0] = pp0;
  4541. if (!this._raw) {
  4542. this._normals[0].normalize();
  4543. }
  4544. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4545. if (!this._raw) {
  4546. this._binormals[0].normalize();
  4547. }
  4548. this._distances[0] = 0.0;
  4549. // normals and binormals : next points
  4550. var prev; // previous vector (segment)
  4551. var cur; // current vector (segment)
  4552. var curTang; // current tangent
  4553. // previous normal
  4554. var prevBinor; // previous binormal
  4555. for (var i = 1; i < l; i++) {
  4556. // tangents
  4557. prev = this._getLastNonNullVector(i);
  4558. if (i < l - 1) {
  4559. cur = this._getFirstNonNullVector(i);
  4560. this._tangents[i] = prev.add(cur);
  4561. this._tangents[i].normalize();
  4562. }
  4563. this._distances[i] = this._distances[i - 1] + prev.length();
  4564. // normals and binormals
  4565. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4566. curTang = this._tangents[i];
  4567. prevBinor = this._binormals[i - 1];
  4568. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4569. if (!this._raw) {
  4570. this._normals[i].normalize();
  4571. }
  4572. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4573. if (!this._raw) {
  4574. this._binormals[i].normalize();
  4575. }
  4576. }
  4577. };
  4578. // private function getFirstNonNullVector(index)
  4579. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4580. Path3D.prototype._getFirstNonNullVector = function (index) {
  4581. var i = 1;
  4582. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4583. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4584. i++;
  4585. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4586. }
  4587. return nNVector;
  4588. };
  4589. // private function getLastNonNullVector(index)
  4590. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4591. Path3D.prototype._getLastNonNullVector = function (index) {
  4592. var i = 1;
  4593. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4594. while (nLVector.length() === 0 && index > i + 1) {
  4595. i++;
  4596. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4597. }
  4598. return nLVector;
  4599. };
  4600. // private function normalVector(v0, vt, va) :
  4601. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4602. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4603. Path3D.prototype._normalVector = function (v0, vt, va) {
  4604. var normal0;
  4605. var tgl = vt.length();
  4606. if (tgl === 0.0) {
  4607. tgl = 1.0;
  4608. }
  4609. if (va === undefined || va === null) {
  4610. var point;
  4611. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4612. point = new Vector3(0.0, -1.0, 0.0);
  4613. }
  4614. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4615. point = new Vector3(1.0, 0.0, 0.0);
  4616. }
  4617. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4618. point = new Vector3(0.0, 0.0, 1.0);
  4619. }
  4620. normal0 = Vector3.Cross(vt, point);
  4621. }
  4622. else {
  4623. normal0 = Vector3.Cross(vt, va);
  4624. Vector3.CrossToRef(normal0, vt, normal0);
  4625. }
  4626. normal0.normalize();
  4627. return normal0;
  4628. };
  4629. return Path3D;
  4630. }());
  4631. BABYLON.Path3D = Path3D;
  4632. var Curve3 = (function () {
  4633. /**
  4634. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4635. * A Curve3 is designed from a series of successive Vector3.
  4636. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4637. */
  4638. function Curve3(points) {
  4639. this._length = 0.0;
  4640. this._points = points;
  4641. this._length = this._computeLength(points);
  4642. }
  4643. /**
  4644. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4645. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4646. * @param v1 (Vector3) the control point
  4647. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4648. * @param nbPoints (integer) the wanted number of points in the curve
  4649. */
  4650. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4651. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4652. var bez = new Array();
  4653. var equation = function (t, val0, val1, val2) {
  4654. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4655. return res;
  4656. };
  4657. for (var i = 0; i <= nbPoints; i++) {
  4658. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4659. }
  4660. return new Curve3(bez);
  4661. };
  4662. /**
  4663. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4664. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4665. * @param v1 (Vector3) the first control point
  4666. * @param v2 (Vector3) the second control point
  4667. * @param v3 (Vector3) the end point of the Cubic Bezier
  4668. * @param nbPoints (integer) the wanted number of points in the curve
  4669. */
  4670. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4671. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4672. var bez = new Array();
  4673. var equation = function (t, val0, val1, val2, val3) {
  4674. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4675. return res;
  4676. };
  4677. for (var i = 0; i <= nbPoints; i++) {
  4678. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4679. }
  4680. return new Curve3(bez);
  4681. };
  4682. /**
  4683. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4684. * @param p1 (Vector3) the origin point of the Hermite Spline
  4685. * @param t1 (Vector3) the tangent vector at the origin point
  4686. * @param p2 (Vector3) the end point of the Hermite Spline
  4687. * @param t2 (Vector3) the tangent vector at the end point
  4688. * @param nbPoints (integer) the wanted number of points in the curve
  4689. */
  4690. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4691. var hermite = new Array();
  4692. var step = 1.0 / nbPoints;
  4693. for (var i = 0; i <= nbPoints; i++) {
  4694. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4695. }
  4696. return new Curve3(hermite);
  4697. };
  4698. /**
  4699. * Returns a Curve3 object along a CatmullRom Spline curve :
  4700. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4701. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4702. */
  4703. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4704. var totalPoints = new Array();
  4705. totalPoints.push(points[0].clone());
  4706. Array.prototype.push.apply(totalPoints, points);
  4707. totalPoints.push(points[points.length - 1].clone());
  4708. var catmullRom = new Array();
  4709. var step = 1.0 / nbPoints;
  4710. for (var i = 0; i < totalPoints.length - 3; i++) {
  4711. var amount = 0.0;
  4712. for (var c = 0; c < nbPoints; c++) {
  4713. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4714. amount += step;
  4715. }
  4716. }
  4717. i--;
  4718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4719. return new Curve3(catmullRom);
  4720. };
  4721. /**
  4722. * Returns the Curve3 stored array of successive Vector3
  4723. */
  4724. Curve3.prototype.getPoints = function () {
  4725. return this._points;
  4726. };
  4727. /**
  4728. * Returns the computed length (float) of the curve.
  4729. */
  4730. Curve3.prototype.length = function () {
  4731. return this._length;
  4732. };
  4733. /**
  4734. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4735. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4736. * curveA and curveB keep unchanged.
  4737. */
  4738. Curve3.prototype.continue = function (curve) {
  4739. var lastPoint = this._points[this._points.length - 1];
  4740. var continuedPoints = this._points.slice();
  4741. var curvePoints = curve.getPoints();
  4742. for (var i = 1; i < curvePoints.length; i++) {
  4743. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4744. }
  4745. var continuedCurve = new Curve3(continuedPoints);
  4746. return continuedCurve;
  4747. };
  4748. Curve3.prototype._computeLength = function (path) {
  4749. var l = 0;
  4750. for (var i = 1; i < path.length; i++) {
  4751. l += (path[i].subtract(path[i - 1])).length();
  4752. }
  4753. return l;
  4754. };
  4755. return Curve3;
  4756. }());
  4757. BABYLON.Curve3 = Curve3;
  4758. // Vertex formats
  4759. var PositionNormalVertex = (function () {
  4760. function PositionNormalVertex(position, normal) {
  4761. if (position === void 0) { position = Vector3.Zero(); }
  4762. if (normal === void 0) { normal = Vector3.Up(); }
  4763. this.position = position;
  4764. this.normal = normal;
  4765. }
  4766. PositionNormalVertex.prototype.clone = function () {
  4767. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4768. };
  4769. return PositionNormalVertex;
  4770. }());
  4771. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4772. var PositionNormalTextureVertex = (function () {
  4773. function PositionNormalTextureVertex(position, normal, uv) {
  4774. if (position === void 0) { position = Vector3.Zero(); }
  4775. if (normal === void 0) { normal = Vector3.Up(); }
  4776. if (uv === void 0) { uv = Vector2.Zero(); }
  4777. this.position = position;
  4778. this.normal = normal;
  4779. this.uv = uv;
  4780. }
  4781. PositionNormalTextureVertex.prototype.clone = function () {
  4782. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4783. };
  4784. return PositionNormalTextureVertex;
  4785. }());
  4786. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4787. // Temporary pre-allocated objects for engine internal use
  4788. // usage in any internal function :
  4789. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4790. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4791. var Tmp = (function () {
  4792. function Tmp() {
  4793. }
  4794. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4795. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4796. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4797. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4798. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4799. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4800. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4801. Matrix.Zero(), Matrix.Zero(),
  4802. Matrix.Zero(), Matrix.Zero(),
  4803. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4804. return Tmp;
  4805. }());
  4806. BABYLON.Tmp = Tmp;
  4807. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4808. var MathTmp = (function () {
  4809. function MathTmp() {
  4810. }
  4811. MathTmp.Vector3 = [Vector3.Zero()];
  4812. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4813. MathTmp.Quaternion = [Quaternion.Zero()];
  4814. return MathTmp;
  4815. }());
  4816. })(BABYLON || (BABYLON = {}));
  4817. //# sourceMappingURL=babylon.math.js.map
  4818. var BABYLON;
  4819. (function (BABYLON) {
  4820. var Scalar = (function () {
  4821. function Scalar() {
  4822. }
  4823. /**
  4824. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4825. */
  4826. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4827. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4828. var num = a - b;
  4829. return -epsilon <= num && num <= epsilon;
  4830. };
  4831. /**
  4832. * Returns a string : the upper case translation of the number i to hexadecimal.
  4833. */
  4834. Scalar.ToHex = function (i) {
  4835. var str = i.toString(16);
  4836. if (i <= 15) {
  4837. return ("0" + str).toUpperCase();
  4838. }
  4839. return str.toUpperCase();
  4840. };
  4841. /**
  4842. * Returns -1 if value is negative and +1 is value is positive.
  4843. * Returns the value itself if it's equal to zero.
  4844. */
  4845. Scalar.Sign = function (value) {
  4846. value = +value; // convert to a number
  4847. if (value === 0 || isNaN(value))
  4848. return value;
  4849. return value > 0 ? 1 : -1;
  4850. };
  4851. /**
  4852. * Returns the value itself if it's between min and max.
  4853. * Returns min if the value is lower than min.
  4854. * Returns max if the value is greater than max.
  4855. */
  4856. Scalar.Clamp = function (value, min, max) {
  4857. if (min === void 0) { min = 0; }
  4858. if (max === void 0) { max = 1; }
  4859. return Math.min(max, Math.max(min, value));
  4860. };
  4861. /**
  4862. * Returns the log2 of value.
  4863. */
  4864. Scalar.Log2 = function (value) {
  4865. return Math.log(value) * Math.LOG2E;
  4866. };
  4867. /**
  4868. * Loops the value, so that it is never larger than length and never smaller than 0.
  4869. *
  4870. * This is similar to the modulo operator but it works with floating point numbers.
  4871. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4872. * With t = 5 and length = 2.5, the result would be 0.0.
  4873. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4874. */
  4875. Scalar.Repeat = function (value, length) {
  4876. return value - Math.floor(value / length) * length;
  4877. };
  4878. /**
  4879. * Normalize the value between 0.0 and 1.0 using min and max values
  4880. */
  4881. Scalar.Normalize = function (value, min, max) {
  4882. return (value - min) / (max - min);
  4883. };
  4884. /**
  4885. * Denormalize the value from 0.0 and 1.0 using min and max values
  4886. */
  4887. Scalar.Denormalize = function (normalized, min, max) {
  4888. return (normalized * (max - min) + min);
  4889. };
  4890. /**
  4891. * Calculates the shortest difference between two given angles given in degrees.
  4892. */
  4893. Scalar.DeltaAngle = function (current, target) {
  4894. var num = Scalar.Repeat(target - current, 360.0);
  4895. if (num > 180.0) {
  4896. num -= 360.0;
  4897. }
  4898. return num;
  4899. };
  4900. /**
  4901. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4902. *
  4903. * The returned value will move back and forth between 0 and length
  4904. */
  4905. Scalar.PingPong = function (tx, length) {
  4906. var t = Scalar.Repeat(tx, length * 2.0);
  4907. return length - Math.abs(t - length);
  4908. };
  4909. /**
  4910. * Interpolates between min and max with smoothing at the limits.
  4911. *
  4912. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4913. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4914. */
  4915. Scalar.SmoothStep = function (from, to, tx) {
  4916. var t = Scalar.Clamp(tx);
  4917. t = -2.0 * t * t * t + 3.0 * t * t;
  4918. return to * t + from * (1.0 - t);
  4919. };
  4920. /**
  4921. * Moves a value current towards target.
  4922. *
  4923. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4924. * Negative values of maxDelta pushes the value away from target.
  4925. */
  4926. Scalar.MoveTowards = function (current, target, maxDelta) {
  4927. var result = 0;
  4928. if (Math.abs(target - current) <= maxDelta) {
  4929. result = target;
  4930. }
  4931. else {
  4932. result = current + Scalar.Sign(target - current) * maxDelta;
  4933. }
  4934. return result;
  4935. };
  4936. /**
  4937. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4938. *
  4939. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4940. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4941. */
  4942. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4943. var num = Scalar.DeltaAngle(current, target);
  4944. var result = 0;
  4945. if (-maxDelta < num && num < maxDelta) {
  4946. result = target;
  4947. }
  4948. else {
  4949. target = current + num;
  4950. result = Scalar.MoveTowards(current, target, maxDelta);
  4951. }
  4952. return result;
  4953. };
  4954. /**
  4955. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4956. */
  4957. Scalar.Lerp = function (start, end, amount) {
  4958. return start + ((end - start) * amount);
  4959. };
  4960. /**
  4961. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4962. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4963. */
  4964. Scalar.LerpAngle = function (start, end, amount) {
  4965. var num = Scalar.Repeat(end - start, 360.0);
  4966. if (num > 180.0) {
  4967. num -= 360.0;
  4968. }
  4969. return start + num * Scalar.Clamp(amount);
  4970. };
  4971. /**
  4972. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4973. */
  4974. Scalar.InverseLerp = function (a, b, value) {
  4975. var result = 0;
  4976. if (a != b) {
  4977. result = Scalar.Clamp((value - a) / (b - a));
  4978. }
  4979. else {
  4980. result = 0.0;
  4981. }
  4982. return result;
  4983. };
  4984. /**
  4985. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4986. */
  4987. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4988. var squared = amount * amount;
  4989. var cubed = amount * squared;
  4990. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4991. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4992. var part3 = (cubed - (2.0 * squared)) + amount;
  4993. var part4 = cubed - squared;
  4994. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4995. };
  4996. /**
  4997. * Returns a random float number between and min and max values
  4998. */
  4999. Scalar.RandomRange = function (min, max) {
  5000. if (min === max)
  5001. return min;
  5002. return ((Math.random() * (max - min)) + min);
  5003. };
  5004. /**
  5005. * This function returns percentage of a number in a given range.
  5006. *
  5007. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5008. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5009. */
  5010. Scalar.RangeToPercent = function (number, min, max) {
  5011. return ((number - min) / (max - min));
  5012. };
  5013. /**
  5014. * This function returns number that corresponds to the percentage in a given range.
  5015. *
  5016. * PercentToRange(0.34,0,100) will return 34.
  5017. */
  5018. Scalar.PercentToRange = function (percent, min, max) {
  5019. return ((max - min) * percent + min);
  5020. };
  5021. return Scalar;
  5022. }());
  5023. BABYLON.Scalar = Scalar;
  5024. })(BABYLON || (BABYLON = {}));
  5025. //# sourceMappingURL=babylon.math.scalar.js.map
  5026. //# sourceMappingURL=babylon.mixins.js.map
  5027. var BABYLON;
  5028. (function (BABYLON) {
  5029. var __decoratorInitialStore = {};
  5030. var __mergedStore = {};
  5031. var _copySource = function (creationFunction, source, instanciate) {
  5032. var destination = creationFunction();
  5033. // Tags
  5034. if (BABYLON.Tags) {
  5035. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5036. }
  5037. var classStore = getMergedStore(destination);
  5038. // Properties
  5039. for (var property in classStore) {
  5040. var propertyDescriptor = classStore[property];
  5041. var sourceProperty = source[property];
  5042. var propertyType = propertyDescriptor.type;
  5043. if (sourceProperty !== undefined && sourceProperty !== null) {
  5044. switch (propertyType) {
  5045. case 0: // Value
  5046. case 6:// Mesh reference
  5047. destination[property] = sourceProperty;
  5048. break;
  5049. case 1: // Texture
  5050. case 2: // Color3
  5051. case 3: // FresnelParameters
  5052. case 4: // Vector2
  5053. case 5: // Vector3
  5054. case 7:// Color Curves
  5055. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5056. break;
  5057. }
  5058. }
  5059. }
  5060. return destination;
  5061. };
  5062. function getDirectStore(target) {
  5063. var classKey = target.getClassName();
  5064. if (!__decoratorInitialStore[classKey]) {
  5065. __decoratorInitialStore[classKey] = {};
  5066. }
  5067. return __decoratorInitialStore[classKey];
  5068. }
  5069. /**
  5070. * Return the list of properties flagged as serializable
  5071. * @param target: host object
  5072. */
  5073. function getMergedStore(target) {
  5074. var classKey = target.getClassName();
  5075. if (__mergedStore[classKey]) {
  5076. return __mergedStore[classKey];
  5077. }
  5078. __mergedStore[classKey] = {};
  5079. var store = __mergedStore[classKey];
  5080. var currentTarget = target;
  5081. var currentKey = classKey;
  5082. while (currentKey) {
  5083. var initialStore = __decoratorInitialStore[currentKey];
  5084. for (var property in initialStore) {
  5085. store[property] = initialStore[property];
  5086. }
  5087. var parent_1 = void 0;
  5088. var done = false;
  5089. do {
  5090. parent_1 = Object.getPrototypeOf(currentTarget);
  5091. if (!parent_1.getClassName) {
  5092. done = true;
  5093. break;
  5094. }
  5095. if (parent_1.getClassName() !== currentKey) {
  5096. break;
  5097. }
  5098. currentTarget = parent_1;
  5099. } while (parent_1);
  5100. if (done) {
  5101. break;
  5102. }
  5103. currentKey = parent_1.getClassName();
  5104. currentTarget = parent_1;
  5105. }
  5106. return store;
  5107. }
  5108. function generateSerializableMember(type, sourceName) {
  5109. return function (target, propertyKey) {
  5110. var classStore = getDirectStore(target);
  5111. if (!classStore[propertyKey]) {
  5112. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5113. }
  5114. };
  5115. }
  5116. function generateExpandMember(setCallback, targetKey) {
  5117. return function (target, propertyKey) {
  5118. var key = targetKey || ("_" + propertyKey);
  5119. Object.defineProperty(target, propertyKey, {
  5120. get: function () {
  5121. return this[key];
  5122. },
  5123. set: function (value) {
  5124. if (this[key] === value) {
  5125. return;
  5126. }
  5127. this[key] = value;
  5128. target[setCallback].apply(this);
  5129. },
  5130. enumerable: true,
  5131. configurable: true
  5132. });
  5133. };
  5134. }
  5135. function expandToProperty(callback, targetKey) {
  5136. return generateExpandMember(callback, targetKey);
  5137. }
  5138. BABYLON.expandToProperty = expandToProperty;
  5139. function serialize(sourceName) {
  5140. return generateSerializableMember(0, sourceName); // value member
  5141. }
  5142. BABYLON.serialize = serialize;
  5143. function serializeAsTexture(sourceName) {
  5144. return generateSerializableMember(1, sourceName); // texture member
  5145. }
  5146. BABYLON.serializeAsTexture = serializeAsTexture;
  5147. function serializeAsColor3(sourceName) {
  5148. return generateSerializableMember(2, sourceName); // color3 member
  5149. }
  5150. BABYLON.serializeAsColor3 = serializeAsColor3;
  5151. function serializeAsFresnelParameters(sourceName) {
  5152. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5153. }
  5154. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5155. function serializeAsVector2(sourceName) {
  5156. return generateSerializableMember(4, sourceName); // vector2 member
  5157. }
  5158. BABYLON.serializeAsVector2 = serializeAsVector2;
  5159. function serializeAsVector3(sourceName) {
  5160. return generateSerializableMember(5, sourceName); // vector3 member
  5161. }
  5162. BABYLON.serializeAsVector3 = serializeAsVector3;
  5163. function serializeAsMeshReference(sourceName) {
  5164. return generateSerializableMember(6, sourceName); // mesh reference member
  5165. }
  5166. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5167. function serializeAsColorCurves(sourceName) {
  5168. return generateSerializableMember(7, sourceName); // color curves
  5169. }
  5170. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5171. function serializeAsColor4(sourceName) {
  5172. return generateSerializableMember(8, sourceName); // color 4
  5173. }
  5174. BABYLON.serializeAsColor4 = serializeAsColor4;
  5175. function serializeAsImageProcessingConfiguration(sourceName) {
  5176. return generateSerializableMember(9, sourceName); // image processing
  5177. }
  5178. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5179. var SerializationHelper = (function () {
  5180. function SerializationHelper() {
  5181. }
  5182. SerializationHelper.Serialize = function (entity, serializationObject) {
  5183. if (!serializationObject) {
  5184. serializationObject = {};
  5185. }
  5186. // Tags
  5187. if (BABYLON.Tags) {
  5188. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5189. }
  5190. var serializedProperties = getMergedStore(entity);
  5191. // Properties
  5192. for (var property in serializedProperties) {
  5193. var propertyDescriptor = serializedProperties[property];
  5194. var targetPropertyName = propertyDescriptor.sourceName || property;
  5195. var propertyType = propertyDescriptor.type;
  5196. var sourceProperty = entity[property];
  5197. if (sourceProperty !== undefined && sourceProperty !== null) {
  5198. switch (propertyType) {
  5199. case 0:// Value
  5200. serializationObject[targetPropertyName] = sourceProperty;
  5201. break;
  5202. case 1:// Texture
  5203. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5204. break;
  5205. case 2:// Color3
  5206. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5207. break;
  5208. case 3:// FresnelParameters
  5209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5210. break;
  5211. case 4:// Vector2
  5212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5213. break;
  5214. case 5:// Vector3
  5215. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5216. break;
  5217. case 6:// Mesh reference
  5218. serializationObject[targetPropertyName] = sourceProperty.id;
  5219. break;
  5220. case 7:// Color Curves
  5221. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5222. break;
  5223. case 8:// Color 4
  5224. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5225. break;
  5226. case 9:// Image Processing
  5227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5228. break;
  5229. }
  5230. }
  5231. }
  5232. return serializationObject;
  5233. };
  5234. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5235. var destination = creationFunction();
  5236. // Tags
  5237. if (BABYLON.Tags) {
  5238. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5239. }
  5240. var classStore = getMergedStore(destination);
  5241. // Properties
  5242. for (var property in classStore) {
  5243. var propertyDescriptor = classStore[property];
  5244. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5245. var propertyType = propertyDescriptor.type;
  5246. if (sourceProperty !== undefined && sourceProperty !== null) {
  5247. switch (propertyType) {
  5248. case 0:// Value
  5249. destination[property] = sourceProperty;
  5250. break;
  5251. case 1:// Texture
  5252. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5253. break;
  5254. case 2:// Color3
  5255. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5256. break;
  5257. case 3:// FresnelParameters
  5258. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5259. break;
  5260. case 4:// Vector2
  5261. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5262. break;
  5263. case 5:// Vector3
  5264. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5265. break;
  5266. case 6:// Mesh reference
  5267. destination[property] = scene.getLastMeshByID(sourceProperty);
  5268. break;
  5269. case 7:// Color Curves
  5270. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5271. break;
  5272. case 8:// Color 4
  5273. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5274. break;
  5275. case 9:// Image Processing
  5276. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5277. break;
  5278. }
  5279. }
  5280. }
  5281. return destination;
  5282. };
  5283. SerializationHelper.Clone = function (creationFunction, source) {
  5284. return _copySource(creationFunction, source, false);
  5285. };
  5286. SerializationHelper.Instanciate = function (creationFunction, source) {
  5287. return _copySource(creationFunction, source, true);
  5288. };
  5289. return SerializationHelper;
  5290. }());
  5291. BABYLON.SerializationHelper = SerializationHelper;
  5292. })(BABYLON || (BABYLON = {}));
  5293. //# sourceMappingURL=babylon.decorators.js.map
  5294. var BABYLON;
  5295. (function (BABYLON) {
  5296. /**
  5297. * A class serves as a medium between the observable and its observers
  5298. */
  5299. var EventState = (function () {
  5300. /**
  5301. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5302. */
  5303. function EventState(mask, skipNextObservers) {
  5304. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5305. this.initalize(mask, skipNextObservers);
  5306. }
  5307. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5308. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5309. this.mask = mask;
  5310. this.skipNextObservers = skipNextObservers;
  5311. return this;
  5312. };
  5313. return EventState;
  5314. }());
  5315. BABYLON.EventState = EventState;
  5316. /**
  5317. * Represent an Observer registered to a given Observable object.
  5318. */
  5319. var Observer = (function () {
  5320. function Observer(callback, mask) {
  5321. this.callback = callback;
  5322. this.mask = mask;
  5323. }
  5324. return Observer;
  5325. }());
  5326. BABYLON.Observer = Observer;
  5327. /**
  5328. * The Observable class is a simple implementation of the Observable pattern.
  5329. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5330. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5331. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5332. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5333. */
  5334. var Observable = (function () {
  5335. function Observable() {
  5336. this._observers = new Array();
  5337. this._eventState = new EventState(0);
  5338. }
  5339. /**
  5340. * Create a new Observer with the specified callback
  5341. * @param callback the callback that will be executed for that Observer
  5342. * @param mask the mask used to filter observers
  5343. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5344. */
  5345. Observable.prototype.add = function (callback, mask, insertFirst) {
  5346. if (mask === void 0) { mask = -1; }
  5347. if (insertFirst === void 0) { insertFirst = false; }
  5348. if (!callback) {
  5349. return null;
  5350. }
  5351. var observer = new Observer(callback, mask);
  5352. if (insertFirst) {
  5353. this._observers.unshift(observer);
  5354. }
  5355. else {
  5356. this._observers.push(observer);
  5357. }
  5358. return observer;
  5359. };
  5360. /**
  5361. * Remove an Observer from the Observable object
  5362. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5363. */
  5364. Observable.prototype.remove = function (observer) {
  5365. var index = this._observers.indexOf(observer);
  5366. if (index !== -1) {
  5367. this._observers.splice(index, 1);
  5368. return true;
  5369. }
  5370. return false;
  5371. };
  5372. /**
  5373. * Remove a callback from the Observable object
  5374. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5375. */
  5376. Observable.prototype.removeCallback = function (callback) {
  5377. for (var index = 0; index < this._observers.length; index++) {
  5378. if (this._observers[index].callback === callback) {
  5379. this._observers.splice(index, 1);
  5380. return true;
  5381. }
  5382. }
  5383. return false;
  5384. };
  5385. /**
  5386. * Notify all Observers by calling their respective callback with the given data
  5387. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5388. * @param eventData
  5389. * @param mask
  5390. */
  5391. Observable.prototype.notifyObservers = function (eventData, mask) {
  5392. if (mask === void 0) { mask = -1; }
  5393. var state = this._eventState;
  5394. state.mask = mask;
  5395. state.skipNextObservers = false;
  5396. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5397. var obs = _a[_i];
  5398. if (obs.mask & mask) {
  5399. obs.callback(eventData, state);
  5400. }
  5401. if (state.skipNextObservers) {
  5402. return false;
  5403. }
  5404. }
  5405. return true;
  5406. };
  5407. /**
  5408. * return true is the Observable has at least one Observer registered
  5409. */
  5410. Observable.prototype.hasObservers = function () {
  5411. return this._observers.length > 0;
  5412. };
  5413. /**
  5414. * Clear the list of observers
  5415. */
  5416. Observable.prototype.clear = function () {
  5417. this._observers = new Array();
  5418. };
  5419. /**
  5420. * Clone the current observable
  5421. */
  5422. Observable.prototype.clone = function () {
  5423. var result = new Observable();
  5424. result._observers = this._observers.slice(0);
  5425. return result;
  5426. };
  5427. /**
  5428. * Does this observable handles observer registered with a given mask
  5429. * @param {number} trigger - the mask to be tested
  5430. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5431. **/
  5432. Observable.prototype.hasSpecificMask = function (mask) {
  5433. if (mask === void 0) { mask = -1; }
  5434. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5435. var obs = _a[_i];
  5436. if (obs.mask & mask || obs.mask === mask) {
  5437. return true;
  5438. }
  5439. }
  5440. return false;
  5441. };
  5442. return Observable;
  5443. }());
  5444. BABYLON.Observable = Observable;
  5445. })(BABYLON || (BABYLON = {}));
  5446. //# sourceMappingURL=babylon.observable.js.map
  5447. var BABYLON;
  5448. (function (BABYLON) {
  5449. var SmartArray = (function () {
  5450. function SmartArray(capacity) {
  5451. this.length = 0;
  5452. this._duplicateId = 0;
  5453. this.data = new Array(capacity);
  5454. this._id = SmartArray._GlobalId++;
  5455. }
  5456. SmartArray.prototype.push = function (value) {
  5457. this.data[this.length++] = value;
  5458. if (this.length > this.data.length) {
  5459. this.data.length *= 2;
  5460. }
  5461. if (!value.__smartArrayFlags) {
  5462. value.__smartArrayFlags = {};
  5463. }
  5464. value.__smartArrayFlags[this._id] = this._duplicateId;
  5465. };
  5466. SmartArray.prototype.forEach = function (func) {
  5467. for (var index = 0; index < this.length; index++) {
  5468. func(this.data[index]);
  5469. }
  5470. };
  5471. SmartArray.prototype.pushNoDuplicate = function (value) {
  5472. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5473. return false;
  5474. }
  5475. this.push(value);
  5476. return true;
  5477. };
  5478. SmartArray.prototype.sort = function (compareFn) {
  5479. this.data.sort(compareFn);
  5480. };
  5481. SmartArray.prototype.reset = function () {
  5482. this.length = 0;
  5483. this._duplicateId++;
  5484. };
  5485. SmartArray.prototype.dispose = function () {
  5486. this.reset();
  5487. if (this.data) {
  5488. this.data.length = 0;
  5489. this.data = null;
  5490. }
  5491. };
  5492. SmartArray.prototype.concat = function (array) {
  5493. if (array.length === 0) {
  5494. return;
  5495. }
  5496. if (this.length + array.length > this.data.length) {
  5497. this.data.length = (this.length + array.length) * 2;
  5498. }
  5499. for (var index = 0; index < array.length; index++) {
  5500. this.data[this.length++] = (array.data || array)[index];
  5501. }
  5502. };
  5503. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5504. if (array.length === 0) {
  5505. return;
  5506. }
  5507. if (this.length + array.length > this.data.length) {
  5508. this.data.length = (this.length + array.length) * 2;
  5509. }
  5510. for (var index = 0; index < array.length; index++) {
  5511. var item = (array.data || array)[index];
  5512. this.pushNoDuplicate(item);
  5513. }
  5514. };
  5515. SmartArray.prototype.indexOf = function (value) {
  5516. var position = this.data.indexOf(value);
  5517. if (position >= this.length) {
  5518. return -1;
  5519. }
  5520. return position;
  5521. };
  5522. SmartArray.prototype.contains = function (value) {
  5523. return this.data.indexOf(value) !== -1;
  5524. };
  5525. // Statics
  5526. SmartArray._GlobalId = 0;
  5527. return SmartArray;
  5528. }());
  5529. BABYLON.SmartArray = SmartArray;
  5530. })(BABYLON || (BABYLON = {}));
  5531. //# sourceMappingURL=babylon.smartArray.js.map
  5532. var BABYLON;
  5533. (function (BABYLON) {
  5534. // Screenshots
  5535. var screenshotCanvas;
  5536. var cloneValue = function (source, destinationObject) {
  5537. if (!source)
  5538. return null;
  5539. if (source instanceof BABYLON.Mesh) {
  5540. return null;
  5541. }
  5542. if (source instanceof BABYLON.SubMesh) {
  5543. return source.clone(destinationObject);
  5544. }
  5545. else if (source.clone) {
  5546. return source.clone();
  5547. }
  5548. return null;
  5549. };
  5550. var Tools = (function () {
  5551. function Tools() {
  5552. }
  5553. ;
  5554. /**
  5555. * Interpolates between a and b via alpha
  5556. * @param a The lower value (returned when alpha = 0)
  5557. * @param b The upper value (returned when alpha = 1)
  5558. * @param alpha The interpolation-factor
  5559. * @return The mixed value
  5560. */
  5561. Tools.Mix = function (a, b, alpha) {
  5562. return a * (1 - alpha) + b * alpha;
  5563. };
  5564. Tools.Instantiate = function (className) {
  5565. var arr = className.split(".");
  5566. var fn = (window || this);
  5567. for (var i = 0, len = arr.length; i < len; i++) {
  5568. fn = fn[arr[i]];
  5569. }
  5570. if (typeof fn !== "function") {
  5571. return null;
  5572. }
  5573. return fn;
  5574. };
  5575. Tools.SetImmediate = function (action) {
  5576. if (window.setImmediate) {
  5577. window.setImmediate(action);
  5578. }
  5579. else {
  5580. setTimeout(action, 1);
  5581. }
  5582. };
  5583. Tools.IsExponentOfTwo = function (value) {
  5584. var count = 1;
  5585. do {
  5586. count *= 2;
  5587. } while (count < value);
  5588. return count === value;
  5589. };
  5590. /**
  5591. * Find the next highest power of two.
  5592. * @param x Number to start search from.
  5593. * @return Next highest power of two.
  5594. */
  5595. Tools.CeilingPOT = function (x) {
  5596. x--;
  5597. x |= x >> 1;
  5598. x |= x >> 2;
  5599. x |= x >> 4;
  5600. x |= x >> 8;
  5601. x |= x >> 16;
  5602. x++;
  5603. return x;
  5604. };
  5605. /**
  5606. * Find the next lowest power of two.
  5607. * @param x Number to start search from.
  5608. * @return Next lowest power of two.
  5609. */
  5610. Tools.FloorPOT = function (x) {
  5611. x = x | (x >> 1);
  5612. x = x | (x >> 2);
  5613. x = x | (x >> 4);
  5614. x = x | (x >> 8);
  5615. x = x | (x >> 16);
  5616. return x - (x >> 1);
  5617. };
  5618. /**
  5619. * Find the nearest power of two.
  5620. * @param x Number to start search from.
  5621. * @return Next nearest power of two.
  5622. */
  5623. Tools.NearestPOT = function (x) {
  5624. var c = Tools.CeilingPOT(x);
  5625. var f = Tools.FloorPOT(x);
  5626. return (c - x) > (x - f) ? f : c;
  5627. };
  5628. Tools.GetExponentOfTwo = function (value, max, mode) {
  5629. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5630. var pot;
  5631. switch (mode) {
  5632. case BABYLON.Engine.SCALEMODE_FLOOR:
  5633. pot = Tools.FloorPOT(value);
  5634. break;
  5635. case BABYLON.Engine.SCALEMODE_NEAREST:
  5636. pot = Tools.NearestPOT(value);
  5637. break;
  5638. case BABYLON.Engine.SCALEMODE_CEILING:
  5639. pot = Tools.CeilingPOT(value);
  5640. break;
  5641. }
  5642. return Math.min(pot, max);
  5643. };
  5644. Tools.GetFilename = function (path) {
  5645. var index = path.lastIndexOf("/");
  5646. if (index < 0)
  5647. return path;
  5648. return path.substring(index + 1);
  5649. };
  5650. Tools.GetDOMTextContent = function (element) {
  5651. var result = "";
  5652. var child = element.firstChild;
  5653. while (child) {
  5654. if (child.nodeType === 3) {
  5655. result += child.textContent;
  5656. }
  5657. child = child.nextSibling;
  5658. }
  5659. return result;
  5660. };
  5661. Tools.ToDegrees = function (angle) {
  5662. return angle * 180 / Math.PI;
  5663. };
  5664. Tools.ToRadians = function (angle) {
  5665. return angle * Math.PI / 180;
  5666. };
  5667. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5668. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5669. var output = "";
  5670. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5671. var i = 0;
  5672. var bytes = new Uint8Array(buffer);
  5673. while (i < bytes.length) {
  5674. chr1 = bytes[i++];
  5675. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5676. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5677. enc1 = chr1 >> 2;
  5678. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5679. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5680. enc4 = chr3 & 63;
  5681. if (isNaN(chr2)) {
  5682. enc3 = enc4 = 64;
  5683. }
  5684. else if (isNaN(chr3)) {
  5685. enc4 = 64;
  5686. }
  5687. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5688. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5689. }
  5690. return "data:image/png;base64," + output;
  5691. };
  5692. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5693. if (bias === void 0) { bias = null; }
  5694. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5695. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5696. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5697. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5698. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5699. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5700. }
  5701. if (bias) {
  5702. minimum.x -= minimum.x * bias.x + bias.y;
  5703. minimum.y -= minimum.y * bias.x + bias.y;
  5704. minimum.z -= minimum.z * bias.x + bias.y;
  5705. maximum.x += maximum.x * bias.x + bias.y;
  5706. maximum.y += maximum.y * bias.x + bias.y;
  5707. maximum.z += maximum.z * bias.x + bias.y;
  5708. }
  5709. return {
  5710. minimum: minimum,
  5711. maximum: maximum
  5712. };
  5713. };
  5714. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5715. if (bias === void 0) { bias = null; }
  5716. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5717. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5718. if (!stride) {
  5719. stride = 3;
  5720. }
  5721. for (var index = start; index < start + count; index++) {
  5722. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5723. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5724. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5725. }
  5726. if (bias) {
  5727. minimum.x -= minimum.x * bias.x + bias.y;
  5728. minimum.y -= minimum.y * bias.x + bias.y;
  5729. minimum.z -= minimum.z * bias.x + bias.y;
  5730. maximum.x += maximum.x * bias.x + bias.y;
  5731. maximum.y += maximum.y * bias.x + bias.y;
  5732. maximum.z += maximum.z * bias.x + bias.y;
  5733. }
  5734. return {
  5735. minimum: minimum,
  5736. maximum: maximum
  5737. };
  5738. };
  5739. Tools.Vector2ArrayFeeder = function (array) {
  5740. return function (index) {
  5741. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5742. var length = isFloatArray ? array.length / 2 : array.length;
  5743. if (index >= length) {
  5744. return null;
  5745. }
  5746. if (isFloatArray) {
  5747. var fa = array;
  5748. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5749. }
  5750. var a = array;
  5751. return a[index];
  5752. };
  5753. };
  5754. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5755. if (bias === void 0) { bias = null; }
  5756. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5757. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5758. var i = 0;
  5759. var cur = feeder(i++);
  5760. while (cur) {
  5761. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5762. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5763. cur = feeder(i++);
  5764. }
  5765. if (bias) {
  5766. minimum.x -= minimum.x * bias.x + bias.y;
  5767. minimum.y -= minimum.y * bias.x + bias.y;
  5768. maximum.x += maximum.x * bias.x + bias.y;
  5769. maximum.y += maximum.y * bias.x + bias.y;
  5770. }
  5771. return {
  5772. minimum: minimum,
  5773. maximum: maximum
  5774. };
  5775. };
  5776. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5777. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5778. return undefined;
  5779. return Array.isArray(obj) ? obj : [obj];
  5780. };
  5781. // Misc.
  5782. Tools.GetPointerPrefix = function () {
  5783. var eventPrefix = "pointer";
  5784. // Check if pointer events are supported
  5785. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5786. eventPrefix = "mouse";
  5787. }
  5788. return eventPrefix;
  5789. };
  5790. /**
  5791. * @param func - the function to be called
  5792. * @param requester - the object that will request the next frame. Falls back to window.
  5793. */
  5794. Tools.QueueNewFrame = function (func, requester) {
  5795. if (requester === void 0) { requester = window; }
  5796. if (requester.requestAnimationFrame) {
  5797. return requester.requestAnimationFrame(func);
  5798. }
  5799. else if (requester.msRequestAnimationFrame) {
  5800. return requester.msRequestAnimationFrame(func);
  5801. }
  5802. else if (requester.webkitRequestAnimationFrame) {
  5803. return requester.webkitRequestAnimationFrame(func);
  5804. }
  5805. else if (requester.mozRequestAnimationFrame) {
  5806. return requester.mozRequestAnimationFrame(func);
  5807. }
  5808. else if (requester.oRequestAnimationFrame) {
  5809. return requester.oRequestAnimationFrame(func);
  5810. }
  5811. else {
  5812. return window.setTimeout(func, 16);
  5813. }
  5814. };
  5815. Tools.RequestFullscreen = function (element) {
  5816. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5817. if (!requestFunction)
  5818. return;
  5819. requestFunction.call(element);
  5820. };
  5821. Tools.ExitFullscreen = function () {
  5822. if (document.exitFullscreen) {
  5823. document.exitFullscreen();
  5824. }
  5825. else if (document.mozCancelFullScreen) {
  5826. document.mozCancelFullScreen();
  5827. }
  5828. else if (document.webkitCancelFullScreen) {
  5829. document.webkitCancelFullScreen();
  5830. }
  5831. else if (document.msCancelFullScreen) {
  5832. document.msCancelFullScreen();
  5833. }
  5834. };
  5835. Tools.SetCorsBehavior = function (url, img) {
  5836. if (Tools.CorsBehavior) {
  5837. switch (typeof (Tools.CorsBehavior)) {
  5838. case "function":
  5839. var result = Tools.CorsBehavior(url);
  5840. if (result) {
  5841. img.crossOrigin = result;
  5842. }
  5843. break;
  5844. case "string":
  5845. default:
  5846. img.crossOrigin = Tools.CorsBehavior;
  5847. break;
  5848. }
  5849. }
  5850. };
  5851. // External files
  5852. Tools.CleanUrl = function (url) {
  5853. url = url.replace(/#/mg, "%23");
  5854. return url;
  5855. };
  5856. Tools.LoadImage = function (url, onload, onerror, database) {
  5857. if (url instanceof ArrayBuffer) {
  5858. url = Tools.EncodeArrayBufferTobase64(url);
  5859. }
  5860. url = Tools.CleanUrl(url);
  5861. url = Tools.PreprocessUrl(url);
  5862. var img = new Image();
  5863. if (url.substr(0, 5) !== "data:") {
  5864. Tools.SetCorsBehavior(url, img);
  5865. }
  5866. img.onload = function () {
  5867. onload(img);
  5868. };
  5869. img.onerror = function (err) {
  5870. Tools.Error("Error while trying to load image: " + url);
  5871. if (Tools.UseFallbackTexture) {
  5872. img.src = Tools.fallbackTexture;
  5873. onload(img);
  5874. }
  5875. else {
  5876. onerror();
  5877. }
  5878. };
  5879. var noIndexedDB = function () {
  5880. img.src = url;
  5881. };
  5882. var loadFromIndexedDB = function () {
  5883. database.loadImageFromDB(url, img);
  5884. };
  5885. //ANY database to do!
  5886. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5887. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5888. }
  5889. else {
  5890. if (url.indexOf("file:") !== 0) {
  5891. noIndexedDB();
  5892. }
  5893. else {
  5894. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5895. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5896. try {
  5897. var blobURL;
  5898. try {
  5899. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5900. }
  5901. catch (ex) {
  5902. // Chrome doesn't support oneTimeOnly parameter
  5903. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5904. }
  5905. img.src = blobURL;
  5906. }
  5907. catch (e) {
  5908. img.src = null;
  5909. }
  5910. }
  5911. else {
  5912. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5913. img.src = Tools.fallbackTexture;
  5914. }
  5915. }
  5916. }
  5917. return img;
  5918. };
  5919. //ANY
  5920. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5921. url = Tools.CleanUrl(url);
  5922. url = Tools.PreprocessUrl(url);
  5923. var noIndexedDB = function () {
  5924. var request = new XMLHttpRequest();
  5925. var loadUrl = Tools.BaseUrl + url;
  5926. request.open('GET', loadUrl, true);
  5927. if (useArrayBuffer) {
  5928. request.responseType = "arraybuffer";
  5929. }
  5930. request.onprogress = progressCallBack;
  5931. request.onreadystatechange = function () {
  5932. // In case of undefined state in some browsers.
  5933. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5934. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5935. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5936. callback(!useArrayBuffer ? request.responseText : request.response);
  5937. }
  5938. else {
  5939. if (onError) {
  5940. onError(request);
  5941. }
  5942. else {
  5943. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5944. }
  5945. }
  5946. }
  5947. };
  5948. request.send(null);
  5949. };
  5950. var loadFromIndexedDB = function () {
  5951. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5952. };
  5953. if (url.indexOf("file:") !== -1) {
  5954. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5955. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5956. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5957. }
  5958. else {
  5959. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5960. }
  5961. }
  5962. else {
  5963. // Caching all files
  5964. if (database && database.enableSceneOffline) {
  5965. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5966. }
  5967. else {
  5968. noIndexedDB();
  5969. }
  5970. }
  5971. };
  5972. /**
  5973. * Load a script (identified by an url). When the url returns, the
  5974. * content of this file is added into a new script element, attached to the DOM (body element)
  5975. */
  5976. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5977. var head = document.getElementsByTagName('head')[0];
  5978. var script = document.createElement('script');
  5979. script.type = 'text/javascript';
  5980. script.src = scriptUrl;
  5981. var self = this;
  5982. script.onload = function () {
  5983. if (onSuccess) {
  5984. onSuccess();
  5985. }
  5986. };
  5987. script.onerror = function () {
  5988. if (onError) {
  5989. onError();
  5990. }
  5991. };
  5992. head.appendChild(script);
  5993. };
  5994. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5995. var reader = new FileReader();
  5996. reader.onload = function (e) {
  5997. //target doesn't have result from ts 1.3
  5998. callback(e.target['result']);
  5999. };
  6000. reader.onprogress = progressCallback;
  6001. reader.readAsDataURL(fileToLoad);
  6002. };
  6003. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6004. var reader = new FileReader();
  6005. reader.onerror = function (e) {
  6006. Tools.Log("Error while reading file: " + fileToLoad.name);
  6007. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6008. };
  6009. reader.onload = function (e) {
  6010. //target doesn't have result from ts 1.3
  6011. callback(e.target['result']);
  6012. };
  6013. reader.onprogress = progressCallBack;
  6014. if (!useArrayBuffer) {
  6015. // Asynchronous read
  6016. reader.readAsText(fileToLoad);
  6017. }
  6018. else {
  6019. reader.readAsArrayBuffer(fileToLoad);
  6020. }
  6021. };
  6022. //returns a downloadable url to a file content.
  6023. Tools.FileAsURL = function (content) {
  6024. var fileBlob = new Blob([content]);
  6025. var url = window.URL || window.webkitURL;
  6026. var link = url.createObjectURL(fileBlob);
  6027. return link;
  6028. };
  6029. // Misc.
  6030. Tools.Format = function (value, decimals) {
  6031. if (decimals === void 0) { decimals = 2; }
  6032. return value.toFixed(decimals);
  6033. };
  6034. Tools.CheckExtends = function (v, min, max) {
  6035. if (v.x < min.x)
  6036. min.x = v.x;
  6037. if (v.y < min.y)
  6038. min.y = v.y;
  6039. if (v.z < min.z)
  6040. min.z = v.z;
  6041. if (v.x > max.x)
  6042. max.x = v.x;
  6043. if (v.y > max.y)
  6044. max.y = v.y;
  6045. if (v.z > max.z)
  6046. max.z = v.z;
  6047. };
  6048. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6049. for (var prop in source) {
  6050. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6051. continue;
  6052. }
  6053. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6054. continue;
  6055. }
  6056. var sourceValue = source[prop];
  6057. var typeOfSourceValue = typeof sourceValue;
  6058. if (typeOfSourceValue === "function") {
  6059. continue;
  6060. }
  6061. if (typeOfSourceValue === "object") {
  6062. if (sourceValue instanceof Array) {
  6063. destination[prop] = [];
  6064. if (sourceValue.length > 0) {
  6065. if (typeof sourceValue[0] == "object") {
  6066. for (var index = 0; index < sourceValue.length; index++) {
  6067. var clonedValue = cloneValue(sourceValue[index], destination);
  6068. if (destination[prop].indexOf(clonedValue) === -1) {
  6069. destination[prop].push(clonedValue);
  6070. }
  6071. }
  6072. }
  6073. else {
  6074. destination[prop] = sourceValue.slice(0);
  6075. }
  6076. }
  6077. }
  6078. else {
  6079. destination[prop] = cloneValue(sourceValue, destination);
  6080. }
  6081. }
  6082. else {
  6083. destination[prop] = sourceValue;
  6084. }
  6085. }
  6086. };
  6087. Tools.IsEmpty = function (obj) {
  6088. for (var i in obj) {
  6089. return false;
  6090. }
  6091. return true;
  6092. };
  6093. Tools.RegisterTopRootEvents = function (events) {
  6094. for (var index = 0; index < events.length; index++) {
  6095. var event = events[index];
  6096. window.addEventListener(event.name, event.handler, false);
  6097. try {
  6098. if (window.parent) {
  6099. window.parent.addEventListener(event.name, event.handler, false);
  6100. }
  6101. }
  6102. catch (e) {
  6103. // Silently fails...
  6104. }
  6105. }
  6106. };
  6107. Tools.UnregisterTopRootEvents = function (events) {
  6108. for (var index = 0; index < events.length; index++) {
  6109. var event = events[index];
  6110. window.removeEventListener(event.name, event.handler);
  6111. try {
  6112. if (window.parent) {
  6113. window.parent.removeEventListener(event.name, event.handler);
  6114. }
  6115. }
  6116. catch (e) {
  6117. // Silently fails...
  6118. }
  6119. }
  6120. };
  6121. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6122. if (mimeType === void 0) { mimeType = "image/png"; }
  6123. // Read the contents of the framebuffer
  6124. var numberOfChannelsByLine = width * 4;
  6125. var halfHeight = height / 2;
  6126. //Reading datas from WebGL
  6127. var data = engine.readPixels(0, 0, width, height);
  6128. //To flip image on Y axis.
  6129. for (var i = 0; i < halfHeight; i++) {
  6130. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6131. var currentCell = j + i * numberOfChannelsByLine;
  6132. var targetLine = height - i - 1;
  6133. var targetCell = j + targetLine * numberOfChannelsByLine;
  6134. var temp = data[currentCell];
  6135. data[currentCell] = data[targetCell];
  6136. data[targetCell] = temp;
  6137. }
  6138. }
  6139. // Create a 2D canvas to store the result
  6140. if (!screenshotCanvas) {
  6141. screenshotCanvas = document.createElement('canvas');
  6142. }
  6143. screenshotCanvas.width = width;
  6144. screenshotCanvas.height = height;
  6145. var context = screenshotCanvas.getContext('2d');
  6146. // Copy the pixels to a 2D canvas
  6147. var imageData = context.createImageData(width, height);
  6148. var castData = (imageData.data);
  6149. castData.set(data);
  6150. context.putImageData(imageData, 0, 0);
  6151. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6152. };
  6153. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6154. if (mimeType === void 0) { mimeType = "image/png"; }
  6155. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6156. if (successCallback) {
  6157. successCallback(base64Image);
  6158. }
  6159. else {
  6160. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6161. if (("download" in document.createElement("a"))) {
  6162. var a = window.document.createElement("a");
  6163. a.href = base64Image;
  6164. var date = new Date();
  6165. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6166. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6167. window.document.body.appendChild(a);
  6168. a.addEventListener("click", function () {
  6169. a.parentElement.removeChild(a);
  6170. });
  6171. a.click();
  6172. //Or opening a new tab with the image if it is not possible to automatically start download.
  6173. }
  6174. else {
  6175. var newWindow = window.open("");
  6176. var img = newWindow.document.createElement("img");
  6177. img.src = base64Image;
  6178. newWindow.document.body.appendChild(img);
  6179. }
  6180. }
  6181. };
  6182. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6183. if (mimeType === void 0) { mimeType = "image/png"; }
  6184. var width;
  6185. var height;
  6186. // If a precision value is specified
  6187. if (size.precision) {
  6188. width = Math.round(engine.getRenderWidth() * size.precision);
  6189. height = Math.round(width / engine.getAspectRatio(camera));
  6190. }
  6191. else if (size.width && size.height) {
  6192. width = size.width;
  6193. height = size.height;
  6194. }
  6195. else if (size.width && !size.height) {
  6196. width = size.width;
  6197. height = Math.round(width / engine.getAspectRatio(camera));
  6198. }
  6199. else if (size.height && !size.width) {
  6200. height = size.height;
  6201. width = Math.round(height * engine.getAspectRatio(camera));
  6202. }
  6203. else if (!isNaN(size)) {
  6204. height = size;
  6205. width = size;
  6206. }
  6207. else {
  6208. Tools.Error("Invalid 'size' parameter !");
  6209. return;
  6210. }
  6211. if (!screenshotCanvas) {
  6212. screenshotCanvas = document.createElement('canvas');
  6213. }
  6214. screenshotCanvas.width = width;
  6215. screenshotCanvas.height = height;
  6216. var renderContext = screenshotCanvas.getContext("2d");
  6217. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6218. var newWidth = width;
  6219. var newHeight = newWidth / ratio;
  6220. if (newHeight > height) {
  6221. newHeight = height;
  6222. newWidth = newHeight * ratio;
  6223. }
  6224. var offsetX = Math.max(0, width - newWidth) / 2;
  6225. var offsetY = Math.max(0, height - newHeight) / 2;
  6226. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6227. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6228. };
  6229. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6230. if (mimeType === void 0) { mimeType = "image/png"; }
  6231. if (samples === void 0) { samples = 1; }
  6232. var width;
  6233. var height;
  6234. //If a precision value is specified
  6235. if (size.precision) {
  6236. width = Math.round(engine.getRenderWidth() * size.precision);
  6237. height = Math.round(width / engine.getAspectRatio(camera));
  6238. size = { width: width, height: height };
  6239. }
  6240. else if (size.width && size.height) {
  6241. width = size.width;
  6242. height = size.height;
  6243. }
  6244. else if (size.width && !size.height) {
  6245. width = size.width;
  6246. height = Math.round(width / engine.getAspectRatio(camera));
  6247. size = { width: width, height: height };
  6248. }
  6249. else if (size.height && !size.width) {
  6250. height = size.height;
  6251. width = Math.round(height * engine.getAspectRatio(camera));
  6252. size = { width: width, height: height };
  6253. }
  6254. else if (!isNaN(size)) {
  6255. height = size;
  6256. width = size;
  6257. }
  6258. else {
  6259. Tools.Error("Invalid 'size' parameter !");
  6260. return;
  6261. }
  6262. var scene = camera.getScene();
  6263. var previousCamera = null;
  6264. if (scene.activeCamera !== camera) {
  6265. previousCamera = scene.activeCamera;
  6266. scene.activeCamera = camera;
  6267. }
  6268. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6269. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6270. texture.renderList = null;
  6271. texture.samples = samples;
  6272. texture.onAfterRenderObservable.add(function () {
  6273. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6274. });
  6275. scene.incrementRenderId();
  6276. scene.resetCachedMaterial();
  6277. texture.render(true);
  6278. texture.dispose();
  6279. if (previousCamera) {
  6280. scene.activeCamera = previousCamera;
  6281. }
  6282. camera.getProjectionMatrix(true); // Force cache refresh;
  6283. };
  6284. // XHR response validator for local file scenario
  6285. Tools.ValidateXHRData = function (xhr, dataType) {
  6286. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6287. if (dataType === void 0) { dataType = 7; }
  6288. try {
  6289. if (dataType & 1) {
  6290. if (xhr.responseText && xhr.responseText.length > 0) {
  6291. return true;
  6292. }
  6293. else if (dataType === 1) {
  6294. return false;
  6295. }
  6296. }
  6297. if (dataType & 2) {
  6298. // Check header width and height since there is no "TGA" magic number
  6299. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6300. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6301. return true;
  6302. }
  6303. else if (dataType === 2) {
  6304. return false;
  6305. }
  6306. }
  6307. if (dataType & 4) {
  6308. // Check for the "DDS" magic number
  6309. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6310. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6311. return true;
  6312. }
  6313. else {
  6314. return false;
  6315. }
  6316. }
  6317. }
  6318. catch (e) {
  6319. // Global protection
  6320. }
  6321. return false;
  6322. };
  6323. /**
  6324. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6325. * Be aware Math.random() could cause collisions, but:
  6326. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  6327. */
  6328. Tools.RandomId = function () {
  6329. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6330. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6331. return v.toString(16);
  6332. });
  6333. };
  6334. Object.defineProperty(Tools, "NoneLogLevel", {
  6335. get: function () {
  6336. return Tools._NoneLogLevel;
  6337. },
  6338. enumerable: true,
  6339. configurable: true
  6340. });
  6341. Object.defineProperty(Tools, "MessageLogLevel", {
  6342. get: function () {
  6343. return Tools._MessageLogLevel;
  6344. },
  6345. enumerable: true,
  6346. configurable: true
  6347. });
  6348. Object.defineProperty(Tools, "WarningLogLevel", {
  6349. get: function () {
  6350. return Tools._WarningLogLevel;
  6351. },
  6352. enumerable: true,
  6353. configurable: true
  6354. });
  6355. Object.defineProperty(Tools, "ErrorLogLevel", {
  6356. get: function () {
  6357. return Tools._ErrorLogLevel;
  6358. },
  6359. enumerable: true,
  6360. configurable: true
  6361. });
  6362. Object.defineProperty(Tools, "AllLogLevel", {
  6363. get: function () {
  6364. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6365. },
  6366. enumerable: true,
  6367. configurable: true
  6368. });
  6369. Tools._AddLogEntry = function (entry) {
  6370. Tools._LogCache = entry + Tools._LogCache;
  6371. if (Tools.OnNewCacheEntry) {
  6372. Tools.OnNewCacheEntry(entry);
  6373. }
  6374. };
  6375. Tools._FormatMessage = function (message) {
  6376. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6377. var date = new Date();
  6378. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6379. };
  6380. Tools._LogDisabled = function (message) {
  6381. // nothing to do
  6382. };
  6383. Tools._LogEnabled = function (message) {
  6384. var formattedMessage = Tools._FormatMessage(message);
  6385. console.log("BJS - " + formattedMessage);
  6386. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6387. Tools._AddLogEntry(entry);
  6388. };
  6389. Tools._WarnDisabled = function (message) {
  6390. // nothing to do
  6391. };
  6392. Tools._WarnEnabled = function (message) {
  6393. var formattedMessage = Tools._FormatMessage(message);
  6394. console.warn("BJS - " + formattedMessage);
  6395. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6396. Tools._AddLogEntry(entry);
  6397. };
  6398. Tools._ErrorDisabled = function (message) {
  6399. // nothing to do
  6400. };
  6401. Tools._ErrorEnabled = function (message) {
  6402. Tools.errorsCount++;
  6403. var formattedMessage = Tools._FormatMessage(message);
  6404. console.error("BJS - " + formattedMessage);
  6405. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6406. Tools._AddLogEntry(entry);
  6407. };
  6408. Object.defineProperty(Tools, "LogCache", {
  6409. get: function () {
  6410. return Tools._LogCache;
  6411. },
  6412. enumerable: true,
  6413. configurable: true
  6414. });
  6415. Tools.ClearLogCache = function () {
  6416. Tools._LogCache = "";
  6417. Tools.errorsCount = 0;
  6418. };
  6419. Object.defineProperty(Tools, "LogLevels", {
  6420. set: function (level) {
  6421. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6422. Tools.Log = Tools._LogEnabled;
  6423. }
  6424. else {
  6425. Tools.Log = Tools._LogDisabled;
  6426. }
  6427. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6428. Tools.Warn = Tools._WarnEnabled;
  6429. }
  6430. else {
  6431. Tools.Warn = Tools._WarnDisabled;
  6432. }
  6433. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6434. Tools.Error = Tools._ErrorEnabled;
  6435. }
  6436. else {
  6437. Tools.Error = Tools._ErrorDisabled;
  6438. }
  6439. },
  6440. enumerable: true,
  6441. configurable: true
  6442. });
  6443. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6444. get: function () {
  6445. return Tools._PerformanceNoneLogLevel;
  6446. },
  6447. enumerable: true,
  6448. configurable: true
  6449. });
  6450. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6451. get: function () {
  6452. return Tools._PerformanceUserMarkLogLevel;
  6453. },
  6454. enumerable: true,
  6455. configurable: true
  6456. });
  6457. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6458. get: function () {
  6459. return Tools._PerformanceConsoleLogLevel;
  6460. },
  6461. enumerable: true,
  6462. configurable: true
  6463. });
  6464. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6465. set: function (level) {
  6466. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6467. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6468. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6469. return;
  6470. }
  6471. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6472. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6473. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6474. return;
  6475. }
  6476. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6477. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6478. },
  6479. enumerable: true,
  6480. configurable: true
  6481. });
  6482. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6483. };
  6484. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6485. };
  6486. Tools._StartUserMark = function (counterName, condition) {
  6487. if (condition === void 0) { condition = true; }
  6488. if (!condition || !Tools._performance.mark) {
  6489. return;
  6490. }
  6491. Tools._performance.mark(counterName + "-Begin");
  6492. };
  6493. Tools._EndUserMark = function (counterName, condition) {
  6494. if (condition === void 0) { condition = true; }
  6495. if (!condition || !Tools._performance.mark) {
  6496. return;
  6497. }
  6498. Tools._performance.mark(counterName + "-End");
  6499. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6500. };
  6501. Tools._StartPerformanceConsole = function (counterName, condition) {
  6502. if (condition === void 0) { condition = true; }
  6503. if (!condition) {
  6504. return;
  6505. }
  6506. Tools._StartUserMark(counterName, condition);
  6507. if (console.time) {
  6508. console.time(counterName);
  6509. }
  6510. };
  6511. Tools._EndPerformanceConsole = function (counterName, condition) {
  6512. if (condition === void 0) { condition = true; }
  6513. if (!condition) {
  6514. return;
  6515. }
  6516. Tools._EndUserMark(counterName, condition);
  6517. if (console.time) {
  6518. console.timeEnd(counterName);
  6519. }
  6520. };
  6521. Object.defineProperty(Tools, "Now", {
  6522. get: function () {
  6523. if (window.performance && window.performance.now) {
  6524. return window.performance.now();
  6525. }
  6526. return new Date().getTime();
  6527. },
  6528. enumerable: true,
  6529. configurable: true
  6530. });
  6531. /**
  6532. * This method will return the name of the class used to create the instance of the given object.
  6533. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6534. * @param object the object to get the class name from
  6535. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6536. */
  6537. Tools.GetClassName = function (object, isType) {
  6538. if (isType === void 0) { isType = false; }
  6539. var name = null;
  6540. if (!isType && object.getClassName) {
  6541. name = object.getClassName();
  6542. }
  6543. else {
  6544. if (object instanceof Object) {
  6545. var classObj = isType ? object : Object.getPrototypeOf(object);
  6546. name = classObj.constructor["__bjsclassName__"];
  6547. }
  6548. if (!name) {
  6549. name = typeof object;
  6550. }
  6551. }
  6552. return name;
  6553. };
  6554. Tools.first = function (array, predicate) {
  6555. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6556. var el = array_1[_i];
  6557. if (predicate(el)) {
  6558. return el;
  6559. }
  6560. }
  6561. };
  6562. /**
  6563. * This method will return the name of the full name of the class, including its owning module (if any).
  6564. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6565. * @param object the object to get the class name from
  6566. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6567. */
  6568. Tools.getFullClassName = function (object, isType) {
  6569. if (isType === void 0) { isType = false; }
  6570. var className = null;
  6571. var moduleName = null;
  6572. if (!isType && object.getClassName) {
  6573. className = object.getClassName();
  6574. }
  6575. else {
  6576. if (object instanceof Object) {
  6577. var classObj = isType ? object : Object.getPrototypeOf(object);
  6578. className = classObj.constructor["__bjsclassName__"];
  6579. moduleName = classObj.constructor["__bjsmoduleName__"];
  6580. }
  6581. if (!className) {
  6582. className = typeof object;
  6583. }
  6584. }
  6585. if (!className) {
  6586. return null;
  6587. }
  6588. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6589. };
  6590. /**
  6591. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6592. * @param array
  6593. */
  6594. Tools.arrayOrStringFeeder = function (array) {
  6595. return function (index) {
  6596. if (index >= array.length) {
  6597. return null;
  6598. }
  6599. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6600. if (val && val.getHashCode) {
  6601. val = val.getHashCode();
  6602. }
  6603. if (typeof val === "string") {
  6604. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6605. }
  6606. return val;
  6607. };
  6608. };
  6609. /**
  6610. * Compute the hashCode of a stream of number
  6611. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6612. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6613. * @return the hash code computed
  6614. */
  6615. Tools.hashCodeFromStream = function (feeder) {
  6616. // Based from here: http://stackoverflow.com/a/7616484/802124
  6617. var hash = 0;
  6618. var index = 0;
  6619. var chr = feeder(index++);
  6620. while (chr != null) {
  6621. hash = ((hash << 5) - hash) + chr;
  6622. hash |= 0; // Convert to 32bit integer
  6623. chr = feeder(index++);
  6624. }
  6625. return hash;
  6626. };
  6627. Tools.BaseUrl = "";
  6628. Tools.CorsBehavior = "anonymous";
  6629. Tools.UseFallbackTexture = true;
  6630. // Used in case of a texture loading problem
  6631. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  6632. Tools.PreprocessUrl = function (url) {
  6633. return url;
  6634. };
  6635. // Logs
  6636. Tools._NoneLogLevel = 0;
  6637. Tools._MessageLogLevel = 1;
  6638. Tools._WarningLogLevel = 2;
  6639. Tools._ErrorLogLevel = 4;
  6640. Tools._LogCache = "";
  6641. Tools.errorsCount = 0;
  6642. Tools.Log = Tools._LogEnabled;
  6643. Tools.Warn = Tools._WarnEnabled;
  6644. Tools.Error = Tools._ErrorEnabled;
  6645. // Performances
  6646. Tools._PerformanceNoneLogLevel = 0;
  6647. Tools._PerformanceUserMarkLogLevel = 1;
  6648. Tools._PerformanceConsoleLogLevel = 2;
  6649. Tools._performance = window.performance;
  6650. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6651. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6652. return Tools;
  6653. }());
  6654. BABYLON.Tools = Tools;
  6655. /**
  6656. * This class is used to track a performance counter which is number based.
  6657. * The user has access to many properties which give statistics of different nature
  6658. *
  6659. * The implementer can track two kinds of Performance Counter: time and count
  6660. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6661. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6662. */
  6663. var PerfCounter = (function () {
  6664. function PerfCounter() {
  6665. this._startMonitoringTime = 0;
  6666. this._min = 0;
  6667. this._max = 0;
  6668. this._average = 0;
  6669. this._lastSecAverage = 0;
  6670. this._current = 0;
  6671. this._totalValueCount = 0;
  6672. this._totalAccumulated = 0;
  6673. this._lastSecAccumulated = 0;
  6674. this._lastSecTime = 0;
  6675. this._lastSecValueCount = 0;
  6676. }
  6677. Object.defineProperty(PerfCounter.prototype, "min", {
  6678. /**
  6679. * Returns the smallest value ever
  6680. */
  6681. get: function () {
  6682. return this._min;
  6683. },
  6684. enumerable: true,
  6685. configurable: true
  6686. });
  6687. Object.defineProperty(PerfCounter.prototype, "max", {
  6688. /**
  6689. * Returns the biggest value ever
  6690. */
  6691. get: function () {
  6692. return this._max;
  6693. },
  6694. enumerable: true,
  6695. configurable: true
  6696. });
  6697. Object.defineProperty(PerfCounter.prototype, "average", {
  6698. /**
  6699. * Returns the average value since the performance counter is running
  6700. */
  6701. get: function () {
  6702. return this._average;
  6703. },
  6704. enumerable: true,
  6705. configurable: true
  6706. });
  6707. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6708. /**
  6709. * Returns the average value of the last second the counter was monitored
  6710. */
  6711. get: function () {
  6712. return this._lastSecAverage;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(PerfCounter.prototype, "current", {
  6718. /**
  6719. * Returns the current value
  6720. */
  6721. get: function () {
  6722. return this._current;
  6723. },
  6724. enumerable: true,
  6725. configurable: true
  6726. });
  6727. Object.defineProperty(PerfCounter.prototype, "total", {
  6728. get: function () {
  6729. return this._totalAccumulated;
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. /**
  6735. * Call this method to start monitoring a new frame.
  6736. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6737. */
  6738. PerfCounter.prototype.fetchNewFrame = function () {
  6739. this._totalValueCount++;
  6740. this._current = 0;
  6741. this._lastSecValueCount++;
  6742. };
  6743. /**
  6744. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6745. * @param newCount the count value to add to the monitored count
  6746. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6747. */
  6748. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6749. if (!PerfCounter.Enabled) {
  6750. return;
  6751. }
  6752. this._current += newCount;
  6753. if (fetchResult) {
  6754. this._fetchResult();
  6755. }
  6756. };
  6757. /**
  6758. * Start monitoring this performance counter
  6759. */
  6760. PerfCounter.prototype.beginMonitoring = function () {
  6761. if (!PerfCounter.Enabled) {
  6762. return;
  6763. }
  6764. this._startMonitoringTime = Tools.Now;
  6765. };
  6766. /**
  6767. * Compute the time lapsed since the previous beginMonitoring() call.
  6768. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  6769. */
  6770. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6771. if (newFrame === void 0) { newFrame = true; }
  6772. if (!PerfCounter.Enabled) {
  6773. return;
  6774. }
  6775. if (newFrame) {
  6776. this.fetchNewFrame();
  6777. }
  6778. var currentTime = Tools.Now;
  6779. this._current = currentTime - this._startMonitoringTime;
  6780. if (newFrame) {
  6781. this._fetchResult();
  6782. }
  6783. };
  6784. PerfCounter.prototype._fetchResult = function () {
  6785. this._totalAccumulated += this._current;
  6786. this._lastSecAccumulated += this._current;
  6787. // Min/Max update
  6788. this._min = Math.min(this._min, this._current);
  6789. this._max = Math.max(this._max, this._current);
  6790. this._average = this._totalAccumulated / this._totalValueCount;
  6791. // Reset last sec?
  6792. var now = Tools.Now;
  6793. if ((now - this._lastSecTime) > 1000) {
  6794. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6795. this._lastSecTime = now;
  6796. this._lastSecAccumulated = 0;
  6797. this._lastSecValueCount = 0;
  6798. }
  6799. };
  6800. PerfCounter.Enabled = true;
  6801. return PerfCounter;
  6802. }());
  6803. BABYLON.PerfCounter = PerfCounter;
  6804. /**
  6805. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6806. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6807. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6808. * @param name The name of the class, case should be preserved
  6809. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6810. */
  6811. function className(name, module) {
  6812. return function (target) {
  6813. target["__bjsclassName__"] = name;
  6814. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6815. };
  6816. }
  6817. BABYLON.className = className;
  6818. /**
  6819. * An implementation of a loop for asynchronous functions.
  6820. */
  6821. var AsyncLoop = (function () {
  6822. /**
  6823. * Constroctor.
  6824. * @param iterations the number of iterations.
  6825. * @param _fn the function to run each iteration
  6826. * @param _successCallback the callback that will be called upon succesful execution
  6827. * @param offset starting offset.
  6828. */
  6829. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6830. if (offset === void 0) { offset = 0; }
  6831. this.iterations = iterations;
  6832. this._fn = _fn;
  6833. this._successCallback = _successCallback;
  6834. this.index = offset - 1;
  6835. this._done = false;
  6836. }
  6837. /**
  6838. * Execute the next iteration. Must be called after the last iteration was finished.
  6839. */
  6840. AsyncLoop.prototype.executeNext = function () {
  6841. if (!this._done) {
  6842. if (this.index + 1 < this.iterations) {
  6843. ++this.index;
  6844. this._fn(this);
  6845. }
  6846. else {
  6847. this.breakLoop();
  6848. }
  6849. }
  6850. };
  6851. /**
  6852. * Break the loop and run the success callback.
  6853. */
  6854. AsyncLoop.prototype.breakLoop = function () {
  6855. this._done = true;
  6856. this._successCallback();
  6857. };
  6858. /**
  6859. * Helper function
  6860. */
  6861. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6862. if (offset === void 0) { offset = 0; }
  6863. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6864. loop.executeNext();
  6865. return loop;
  6866. };
  6867. /**
  6868. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6869. * @param iterations total number of iterations
  6870. * @param syncedIterations number of synchronous iterations in each async iteration.
  6871. * @param fn the function to call each iteration.
  6872. * @param callback a success call back that will be called when iterating stops.
  6873. * @param breakFunction a break condition (optional)
  6874. * @param timeout timeout settings for the setTimeout function. default - 0.
  6875. * @constructor
  6876. */
  6877. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6878. if (timeout === void 0) { timeout = 0; }
  6879. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6880. if (breakFunction && breakFunction())
  6881. loop.breakLoop();
  6882. else {
  6883. setTimeout(function () {
  6884. for (var i = 0; i < syncedIterations; ++i) {
  6885. var iteration = (loop.index * syncedIterations) + i;
  6886. if (iteration >= iterations)
  6887. break;
  6888. fn(iteration);
  6889. if (breakFunction && breakFunction()) {
  6890. loop.breakLoop();
  6891. break;
  6892. }
  6893. }
  6894. loop.executeNext();
  6895. }, timeout);
  6896. }
  6897. }, callback);
  6898. };
  6899. return AsyncLoop;
  6900. }());
  6901. BABYLON.AsyncLoop = AsyncLoop;
  6902. })(BABYLON || (BABYLON = {}));
  6903. //# sourceMappingURL=babylon.tools.js.map
  6904. var BABYLON;
  6905. (function (BABYLON) {
  6906. var Internals;
  6907. (function (Internals) {
  6908. var _AlphaState = (function () {
  6909. /**
  6910. * Initializes the state.
  6911. */
  6912. function _AlphaState() {
  6913. this._isAlphaBlendDirty = false;
  6914. this._isBlendFunctionParametersDirty = false;
  6915. this._isBlendEquationParametersDirty = false;
  6916. this._isBlendConstantsDirty = false;
  6917. this._alphaBlend = false;
  6918. this._blendFunctionParameters = new Array(4);
  6919. this._blendEquationParameters = new Array(2);
  6920. this._blendConstants = new Array(4);
  6921. this.reset();
  6922. }
  6923. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6924. get: function () {
  6925. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6926. },
  6927. enumerable: true,
  6928. configurable: true
  6929. });
  6930. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6931. get: function () {
  6932. return this._alphaBlend;
  6933. },
  6934. set: function (value) {
  6935. if (this._alphaBlend === value) {
  6936. return;
  6937. }
  6938. this._alphaBlend = value;
  6939. this._isAlphaBlendDirty = true;
  6940. },
  6941. enumerable: true,
  6942. configurable: true
  6943. });
  6944. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6945. if (this._blendConstants[0] === r &&
  6946. this._blendConstants[1] === g &&
  6947. this._blendConstants[2] === b &&
  6948. this._blendConstants[3] === a) {
  6949. return;
  6950. }
  6951. this._blendConstants[0] = r;
  6952. this._blendConstants[1] = g;
  6953. this._blendConstants[2] = b;
  6954. this._blendConstants[3] = a;
  6955. this._isBlendConstantsDirty = true;
  6956. };
  6957. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6958. if (this._blendFunctionParameters[0] === value0 &&
  6959. this._blendFunctionParameters[1] === value1 &&
  6960. this._blendFunctionParameters[2] === value2 &&
  6961. this._blendFunctionParameters[3] === value3) {
  6962. return;
  6963. }
  6964. this._blendFunctionParameters[0] = value0;
  6965. this._blendFunctionParameters[1] = value1;
  6966. this._blendFunctionParameters[2] = value2;
  6967. this._blendFunctionParameters[3] = value3;
  6968. this._isBlendFunctionParametersDirty = true;
  6969. };
  6970. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6971. if (this._blendEquationParameters[0] === rgb &&
  6972. this._blendEquationParameters[1] === alpha) {
  6973. return;
  6974. }
  6975. this._blendEquationParameters[0] = rgb;
  6976. this._blendEquationParameters[1] = alpha;
  6977. this._isBlendEquationParametersDirty = true;
  6978. };
  6979. _AlphaState.prototype.reset = function () {
  6980. this._alphaBlend = false;
  6981. this._blendFunctionParameters[0] = null;
  6982. this._blendFunctionParameters[1] = null;
  6983. this._blendFunctionParameters[2] = null;
  6984. this._blendFunctionParameters[3] = null;
  6985. this._blendEquationParameters[0] = null;
  6986. this._blendEquationParameters[1] = null;
  6987. this._blendConstants[0] = null;
  6988. this._blendConstants[1] = null;
  6989. this._blendConstants[2] = null;
  6990. this._blendConstants[3] = null;
  6991. this._isAlphaBlendDirty = true;
  6992. this._isBlendFunctionParametersDirty = false;
  6993. this._isBlendEquationParametersDirty = false;
  6994. this._isBlendConstantsDirty = false;
  6995. };
  6996. _AlphaState.prototype.apply = function (gl) {
  6997. if (!this.isDirty) {
  6998. return;
  6999. }
  7000. // Alpha blend
  7001. if (this._isAlphaBlendDirty) {
  7002. if (this._alphaBlend) {
  7003. gl.enable(gl.BLEND);
  7004. }
  7005. else {
  7006. gl.disable(gl.BLEND);
  7007. }
  7008. this._isAlphaBlendDirty = false;
  7009. }
  7010. // Alpha function
  7011. if (this._isBlendFunctionParametersDirty) {
  7012. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7013. this._isBlendFunctionParametersDirty = false;
  7014. }
  7015. // Alpha equation
  7016. if (this._isBlendEquationParametersDirty) {
  7017. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7018. this._isBlendEquationParametersDirty = false;
  7019. }
  7020. // Constants
  7021. if (this._isBlendConstantsDirty) {
  7022. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7023. this._isBlendConstantsDirty = false;
  7024. }
  7025. };
  7026. return _AlphaState;
  7027. }());
  7028. Internals._AlphaState = _AlphaState;
  7029. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7030. })(BABYLON || (BABYLON = {}));
  7031. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7032. var BABYLON;
  7033. (function (BABYLON) {
  7034. var Internals;
  7035. (function (Internals) {
  7036. var _DepthCullingState = (function () {
  7037. /**
  7038. * Initializes the state.
  7039. */
  7040. function _DepthCullingState() {
  7041. this._isDepthTestDirty = false;
  7042. this._isDepthMaskDirty = false;
  7043. this._isDepthFuncDirty = false;
  7044. this._isCullFaceDirty = false;
  7045. this._isCullDirty = false;
  7046. this._isZOffsetDirty = false;
  7047. this.reset();
  7048. }
  7049. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7050. get: function () {
  7051. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7052. },
  7053. enumerable: true,
  7054. configurable: true
  7055. });
  7056. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7057. get: function () {
  7058. return this._zOffset;
  7059. },
  7060. set: function (value) {
  7061. if (this._zOffset === value) {
  7062. return;
  7063. }
  7064. this._zOffset = value;
  7065. this._isZOffsetDirty = true;
  7066. },
  7067. enumerable: true,
  7068. configurable: true
  7069. });
  7070. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7071. get: function () {
  7072. return this._cullFace;
  7073. },
  7074. set: function (value) {
  7075. if (this._cullFace === value) {
  7076. return;
  7077. }
  7078. this._cullFace = value;
  7079. this._isCullFaceDirty = true;
  7080. },
  7081. enumerable: true,
  7082. configurable: true
  7083. });
  7084. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7085. get: function () {
  7086. return this._cull;
  7087. },
  7088. set: function (value) {
  7089. if (this._cull === value) {
  7090. return;
  7091. }
  7092. this._cull = value;
  7093. this._isCullDirty = true;
  7094. },
  7095. enumerable: true,
  7096. configurable: true
  7097. });
  7098. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7099. get: function () {
  7100. return this._depthFunc;
  7101. },
  7102. set: function (value) {
  7103. if (this._depthFunc === value) {
  7104. return;
  7105. }
  7106. this._depthFunc = value;
  7107. this._isDepthFuncDirty = true;
  7108. },
  7109. enumerable: true,
  7110. configurable: true
  7111. });
  7112. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7113. get: function () {
  7114. return this._depthMask;
  7115. },
  7116. set: function (value) {
  7117. if (this._depthMask === value) {
  7118. return;
  7119. }
  7120. this._depthMask = value;
  7121. this._isDepthMaskDirty = true;
  7122. },
  7123. enumerable: true,
  7124. configurable: true
  7125. });
  7126. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7127. get: function () {
  7128. return this._depthTest;
  7129. },
  7130. set: function (value) {
  7131. if (this._depthTest === value) {
  7132. return;
  7133. }
  7134. this._depthTest = value;
  7135. this._isDepthTestDirty = true;
  7136. },
  7137. enumerable: true,
  7138. configurable: true
  7139. });
  7140. _DepthCullingState.prototype.reset = function () {
  7141. this._depthMask = true;
  7142. this._depthTest = true;
  7143. this._depthFunc = null;
  7144. this._cullFace = null;
  7145. this._cull = null;
  7146. this._zOffset = 0;
  7147. this._isDepthTestDirty = true;
  7148. this._isDepthMaskDirty = true;
  7149. this._isDepthFuncDirty = false;
  7150. this._isCullFaceDirty = false;
  7151. this._isCullDirty = false;
  7152. this._isZOffsetDirty = false;
  7153. };
  7154. _DepthCullingState.prototype.apply = function (gl) {
  7155. if (!this.isDirty) {
  7156. return;
  7157. }
  7158. // Cull
  7159. if (this._isCullDirty) {
  7160. if (this.cull) {
  7161. gl.enable(gl.CULL_FACE);
  7162. }
  7163. else {
  7164. gl.disable(gl.CULL_FACE);
  7165. }
  7166. this._isCullDirty = false;
  7167. }
  7168. // Cull face
  7169. if (this._isCullFaceDirty) {
  7170. gl.cullFace(this.cullFace);
  7171. this._isCullFaceDirty = false;
  7172. }
  7173. // Depth mask
  7174. if (this._isDepthMaskDirty) {
  7175. gl.depthMask(this.depthMask);
  7176. this._isDepthMaskDirty = false;
  7177. }
  7178. // Depth test
  7179. if (this._isDepthTestDirty) {
  7180. if (this.depthTest) {
  7181. gl.enable(gl.DEPTH_TEST);
  7182. }
  7183. else {
  7184. gl.disable(gl.DEPTH_TEST);
  7185. }
  7186. this._isDepthTestDirty = false;
  7187. }
  7188. // Depth func
  7189. if (this._isDepthFuncDirty) {
  7190. gl.depthFunc(this.depthFunc);
  7191. this._isDepthFuncDirty = false;
  7192. }
  7193. // zOffset
  7194. if (this._isZOffsetDirty) {
  7195. if (this.zOffset) {
  7196. gl.enable(gl.POLYGON_OFFSET_FILL);
  7197. gl.polygonOffset(this.zOffset, 0);
  7198. }
  7199. else {
  7200. gl.disable(gl.POLYGON_OFFSET_FILL);
  7201. }
  7202. this._isZOffsetDirty = false;
  7203. }
  7204. };
  7205. return _DepthCullingState;
  7206. }());
  7207. Internals._DepthCullingState = _DepthCullingState;
  7208. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7209. })(BABYLON || (BABYLON = {}));
  7210. //# sourceMappingURL=babylon.depthCullingState.js.map
  7211. var BABYLON;
  7212. (function (BABYLON) {
  7213. var Internals;
  7214. (function (Internals) {
  7215. var _StencilState = (function () {
  7216. function _StencilState() {
  7217. this._isStencilTestDirty = false;
  7218. this._isStencilMaskDirty = false;
  7219. this._isStencilFuncDirty = false;
  7220. this._isStencilOpDirty = false;
  7221. this.reset();
  7222. }
  7223. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7224. get: function () {
  7225. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7226. },
  7227. enumerable: true,
  7228. configurable: true
  7229. });
  7230. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7231. get: function () {
  7232. return this._stencilFunc;
  7233. },
  7234. set: function (value) {
  7235. if (this._stencilFunc === value) {
  7236. return;
  7237. }
  7238. this._stencilFunc = value;
  7239. this._isStencilFuncDirty = true;
  7240. },
  7241. enumerable: true,
  7242. configurable: true
  7243. });
  7244. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7245. get: function () {
  7246. return this._stencilFuncRef;
  7247. },
  7248. set: function (value) {
  7249. if (this._stencilFuncRef === value) {
  7250. return;
  7251. }
  7252. this._stencilFuncRef = value;
  7253. this._isStencilFuncDirty = true;
  7254. },
  7255. enumerable: true,
  7256. configurable: true
  7257. });
  7258. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7259. get: function () {
  7260. return this._stencilFuncMask;
  7261. },
  7262. set: function (value) {
  7263. if (this._stencilFuncMask === value) {
  7264. return;
  7265. }
  7266. this._stencilFuncMask = value;
  7267. this._isStencilFuncDirty = true;
  7268. },
  7269. enumerable: true,
  7270. configurable: true
  7271. });
  7272. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7273. get: function () {
  7274. return this._stencilOpStencilFail;
  7275. },
  7276. set: function (value) {
  7277. if (this._stencilOpStencilFail === value) {
  7278. return;
  7279. }
  7280. this._stencilOpStencilFail = value;
  7281. this._isStencilOpDirty = true;
  7282. },
  7283. enumerable: true,
  7284. configurable: true
  7285. });
  7286. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7287. get: function () {
  7288. return this._stencilOpDepthFail;
  7289. },
  7290. set: function (value) {
  7291. if (this._stencilOpDepthFail === value) {
  7292. return;
  7293. }
  7294. this._stencilOpDepthFail = value;
  7295. this._isStencilOpDirty = true;
  7296. },
  7297. enumerable: true,
  7298. configurable: true
  7299. });
  7300. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7301. get: function () {
  7302. return this._stencilOpStencilDepthPass;
  7303. },
  7304. set: function (value) {
  7305. if (this._stencilOpStencilDepthPass === value) {
  7306. return;
  7307. }
  7308. this._stencilOpStencilDepthPass = value;
  7309. this._isStencilOpDirty = true;
  7310. },
  7311. enumerable: true,
  7312. configurable: true
  7313. });
  7314. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7315. get: function () {
  7316. return this._stencilMask;
  7317. },
  7318. set: function (value) {
  7319. if (this._stencilMask === value) {
  7320. return;
  7321. }
  7322. this._stencilMask = value;
  7323. this._isStencilMaskDirty = true;
  7324. },
  7325. enumerable: true,
  7326. configurable: true
  7327. });
  7328. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7329. get: function () {
  7330. return this._stencilTest;
  7331. },
  7332. set: function (value) {
  7333. if (this._stencilTest === value) {
  7334. return;
  7335. }
  7336. this._stencilTest = value;
  7337. this._isStencilTestDirty = true;
  7338. },
  7339. enumerable: true,
  7340. configurable: true
  7341. });
  7342. _StencilState.prototype.reset = function () {
  7343. this._stencilTest = false;
  7344. this._stencilMask = 0xFF;
  7345. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7346. this._stencilFuncRef = 1;
  7347. this._stencilFuncMask = 0xFF;
  7348. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7349. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7350. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7351. this._isStencilTestDirty = true;
  7352. this._isStencilMaskDirty = true;
  7353. this._isStencilFuncDirty = true;
  7354. this._isStencilOpDirty = true;
  7355. };
  7356. _StencilState.prototype.apply = function (gl) {
  7357. if (!this.isDirty) {
  7358. return;
  7359. }
  7360. // Stencil test
  7361. if (this._isStencilTestDirty) {
  7362. if (this.stencilTest) {
  7363. gl.enable(gl.STENCIL_TEST);
  7364. }
  7365. else {
  7366. gl.disable(gl.STENCIL_TEST);
  7367. }
  7368. this._isStencilTestDirty = false;
  7369. }
  7370. // Stencil mask
  7371. if (this._isStencilMaskDirty) {
  7372. gl.stencilMask(this.stencilMask);
  7373. this._isStencilMaskDirty = false;
  7374. }
  7375. // Stencil func
  7376. if (this._isStencilFuncDirty) {
  7377. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7378. this._isStencilFuncDirty = false;
  7379. }
  7380. // Stencil op
  7381. if (this._isStencilOpDirty) {
  7382. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7383. this._isStencilOpDirty = false;
  7384. }
  7385. };
  7386. return _StencilState;
  7387. }());
  7388. Internals._StencilState = _StencilState;
  7389. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7390. })(BABYLON || (BABYLON = {}));
  7391. //# sourceMappingURL=babylon.stencilState.js.map
  7392. var BABYLON;
  7393. (function (BABYLON) {
  7394. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7395. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7396. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7397. gl.compileShader(shader);
  7398. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7399. throw new Error(gl.getShaderInfoLog(shader));
  7400. }
  7401. return shader;
  7402. };
  7403. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7404. var magFilter = gl.NEAREST;
  7405. var minFilter = gl.NEAREST;
  7406. switch (samplingMode) {
  7407. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7408. magFilter = gl.LINEAR;
  7409. if (generateMipMaps) {
  7410. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7411. }
  7412. else {
  7413. minFilter = gl.LINEAR;
  7414. }
  7415. break;
  7416. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7417. magFilter = gl.LINEAR;
  7418. if (generateMipMaps) {
  7419. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7420. }
  7421. else {
  7422. minFilter = gl.LINEAR;
  7423. }
  7424. break;
  7425. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7426. magFilter = gl.NEAREST;
  7427. if (generateMipMaps) {
  7428. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7429. }
  7430. else {
  7431. minFilter = gl.NEAREST;
  7432. }
  7433. break;
  7434. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7435. magFilter = gl.NEAREST;
  7436. if (generateMipMaps) {
  7437. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7438. }
  7439. else {
  7440. minFilter = gl.NEAREST;
  7441. }
  7442. break;
  7443. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7444. magFilter = gl.NEAREST;
  7445. if (generateMipMaps) {
  7446. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7447. }
  7448. else {
  7449. minFilter = gl.LINEAR;
  7450. }
  7451. break;
  7452. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7453. magFilter = gl.NEAREST;
  7454. if (generateMipMaps) {
  7455. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7456. }
  7457. else {
  7458. minFilter = gl.LINEAR;
  7459. }
  7460. break;
  7461. case BABYLON.Texture.NEAREST_LINEAR:
  7462. magFilter = gl.NEAREST;
  7463. minFilter = gl.LINEAR;
  7464. break;
  7465. case BABYLON.Texture.NEAREST_NEAREST:
  7466. magFilter = gl.NEAREST;
  7467. minFilter = gl.NEAREST;
  7468. break;
  7469. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7470. magFilter = gl.LINEAR;
  7471. if (generateMipMaps) {
  7472. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7473. }
  7474. else {
  7475. minFilter = gl.NEAREST;
  7476. }
  7477. break;
  7478. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7479. magFilter = gl.LINEAR;
  7480. if (generateMipMaps) {
  7481. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7482. }
  7483. else {
  7484. minFilter = gl.NEAREST;
  7485. }
  7486. break;
  7487. case BABYLON.Texture.LINEAR_LINEAR:
  7488. magFilter = gl.LINEAR;
  7489. minFilter = gl.LINEAR;
  7490. break;
  7491. case BABYLON.Texture.LINEAR_NEAREST:
  7492. magFilter = gl.LINEAR;
  7493. minFilter = gl.NEAREST;
  7494. break;
  7495. }
  7496. return {
  7497. min: minFilter,
  7498. mag: magFilter
  7499. };
  7500. };
  7501. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7502. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7503. var img;
  7504. var onload = function () {
  7505. loadedImages[index] = img;
  7506. loadedImages._internalCount++;
  7507. if (scene) {
  7508. scene._removePendingData(img);
  7509. }
  7510. if (loadedImages._internalCount === 6) {
  7511. onfinish(loadedImages);
  7512. }
  7513. };
  7514. var onerror = function () {
  7515. if (scene) {
  7516. scene._removePendingData(img);
  7517. }
  7518. if (onErrorCallBack) {
  7519. onErrorCallBack();
  7520. }
  7521. };
  7522. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7523. if (scene) {
  7524. scene._addPendingData(img);
  7525. }
  7526. };
  7527. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7528. if (onError === void 0) { onError = null; }
  7529. var loadedImages = [];
  7530. loadedImages._internalCount = 0;
  7531. for (var index = 0; index < 6; index++) {
  7532. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7533. }
  7534. };
  7535. var BufferPointer = (function () {
  7536. function BufferPointer() {
  7537. }
  7538. return BufferPointer;
  7539. }());
  7540. var InstancingAttributeInfo = (function () {
  7541. function InstancingAttributeInfo() {
  7542. }
  7543. return InstancingAttributeInfo;
  7544. }());
  7545. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7546. /**
  7547. * Define options used to create a render target texture
  7548. */
  7549. var RenderTargetCreationOptions = (function () {
  7550. function RenderTargetCreationOptions() {
  7551. }
  7552. return RenderTargetCreationOptions;
  7553. }());
  7554. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7555. /**
  7556. * Regroup several parameters relative to the browser in use
  7557. */
  7558. var EngineCapabilities = (function () {
  7559. function EngineCapabilities() {
  7560. }
  7561. return EngineCapabilities;
  7562. }());
  7563. BABYLON.EngineCapabilities = EngineCapabilities;
  7564. /**
  7565. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7566. */
  7567. var Engine = (function () {
  7568. /**
  7569. * @constructor
  7570. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7571. * @param {boolean} [antialias] - enable antialias
  7572. * @param options - further options to be sent to the getContext function
  7573. */
  7574. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7575. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7576. var _this = this;
  7577. // Public members
  7578. this.forcePOTTextures = false;
  7579. this.isFullscreen = false;
  7580. this.isPointerLock = false;
  7581. this.cullBackFaces = true;
  7582. this.renderEvenInBackground = true;
  7583. this.preventCacheWipeBetweenFrames = false;
  7584. // To enable/disable IDB support and avoid XHR on .manifest
  7585. this.enableOfflineSupport = false;
  7586. this.scenes = new Array();
  7587. this.postProcesses = new Array();
  7588. // Observables
  7589. /**
  7590. * Observable event triggered each time the rendering canvas is resized
  7591. */
  7592. this.onResizeObservable = new BABYLON.Observable();
  7593. /**
  7594. * Observable event triggered each time the canvas loses focus
  7595. */
  7596. this.onCanvasBlurObservable = new BABYLON.Observable();
  7597. /**
  7598. * Observable event triggered each time the canvas gains focus
  7599. */
  7600. this.onCanvasFocusObservable = new BABYLON.Observable();
  7601. /**
  7602. * Observable event triggered each time the canvas receives pointerout event
  7603. */
  7604. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7605. this._vrExclusivePointerMode = false;
  7606. // Uniform buffers list
  7607. this.disableUniformBuffers = false;
  7608. this._uniformBuffers = new Array();
  7609. this._windowIsBackground = false;
  7610. this._webGLVersion = 1.0;
  7611. this._badOS = false;
  7612. this._badDesktopOS = false;
  7613. this._colorWrite = true;
  7614. this._drawCalls = new BABYLON.PerfCounter();
  7615. this._renderingQueueLaunched = false;
  7616. this._activeRenderLoops = [];
  7617. // Deterministic lockstepMaxSteps
  7618. this._deterministicLockstep = false;
  7619. this._lockstepMaxSteps = 4;
  7620. // Lost context
  7621. this.onContextLostObservable = new BABYLON.Observable();
  7622. this.onContextRestoredObservable = new BABYLON.Observable();
  7623. this._contextWasLost = false;
  7624. this._doNotHandleContextLost = false;
  7625. // FPS
  7626. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7627. this._fps = 60;
  7628. this._deltaTime = 0;
  7629. /**
  7630. * Turn this value on if you want to pause FPS computation when in background
  7631. */
  7632. this.disablePerformanceMonitorInBackground = false;
  7633. // States
  7634. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7635. this._stencilState = new BABYLON.Internals._StencilState();
  7636. this._alphaState = new BABYLON.Internals._AlphaState();
  7637. this._alphaMode = Engine.ALPHA_DISABLE;
  7638. // Cache
  7639. this._internalTexturesCache = new Array();
  7640. this._maxTextureChannels = 16;
  7641. this._activeTexturesCache = {};
  7642. this._compiledEffects = {};
  7643. this._vertexAttribArraysEnabled = [];
  7644. this._uintIndicesCurrentlySet = false;
  7645. this._currentBoundBuffer = new Array();
  7646. this._currentBufferPointers = new Array();
  7647. this._currentInstanceLocations = new Array();
  7648. this._currentInstanceBuffers = new Array();
  7649. this._vaoRecordInProgress = false;
  7650. this._mustWipeVertexAttributes = false;
  7651. // Hardware supported Compressed Textures
  7652. this._texturesSupported = new Array();
  7653. this._onVRFullScreenTriggered = function () {
  7654. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7655. //get the old size before we change
  7656. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7657. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7658. //get the width and height, change the render size
  7659. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7660. var width, height;
  7661. _this.setHardwareScalingLevel(1);
  7662. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7663. }
  7664. else {
  7665. //When the specs are implemented, need to uncomment this.
  7666. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7667. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7668. _this._vrDisplayEnabled = undefined;
  7669. }
  7670. };
  7671. var canvas;
  7672. Engine.Instances.push(this);
  7673. options = options || {};
  7674. if (canvasOrContext.getContext) {
  7675. canvas = canvasOrContext;
  7676. this._renderingCanvas = canvas;
  7677. if (antialias != null) {
  7678. options.antialias = antialias;
  7679. }
  7680. if (options.deterministicLockstep === undefined) {
  7681. options.deterministicLockstep = false;
  7682. }
  7683. if (options.lockstepMaxSteps === undefined) {
  7684. options.lockstepMaxSteps = 4;
  7685. }
  7686. if (options.preserveDrawingBuffer === undefined) {
  7687. options.preserveDrawingBuffer = false;
  7688. }
  7689. if (options.audioEngine === undefined) {
  7690. options.audioEngine = true;
  7691. }
  7692. if (options.stencil === undefined) {
  7693. options.stencil = true;
  7694. }
  7695. this._deterministicLockstep = options.deterministicLockstep;
  7696. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7697. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7698. // GL
  7699. if (!options.disableWebGL2Support) {
  7700. try {
  7701. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7702. if (this._gl) {
  7703. this._webGLVersion = 2.0;
  7704. }
  7705. }
  7706. catch (e) {
  7707. // Do nothing
  7708. }
  7709. }
  7710. if (!this._gl) {
  7711. if (!canvas) {
  7712. throw new Error("The provided canvas is null or undefined.");
  7713. }
  7714. try {
  7715. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7716. }
  7717. catch (e) {
  7718. throw new Error("WebGL not supported");
  7719. }
  7720. }
  7721. if (!this._gl) {
  7722. throw new Error("WebGL not supported");
  7723. }
  7724. this._onCanvasFocus = function () {
  7725. _this.onCanvasFocusObservable.notifyObservers(_this);
  7726. };
  7727. this._onCanvasBlur = function () {
  7728. _this.onCanvasBlurObservable.notifyObservers(_this);
  7729. };
  7730. canvas.addEventListener("focus", this._onCanvasFocus);
  7731. canvas.addEventListener("blur", this._onCanvasBlur);
  7732. this._onBlur = function () {
  7733. if (_this.disablePerformanceMonitorInBackground) {
  7734. _this._performanceMonitor.disable();
  7735. }
  7736. _this._windowIsBackground = true;
  7737. };
  7738. this._onFocus = function () {
  7739. if (_this.disablePerformanceMonitorInBackground) {
  7740. _this._performanceMonitor.enable();
  7741. }
  7742. _this._windowIsBackground = false;
  7743. };
  7744. this._onCanvasPointerOut = function () {
  7745. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7746. };
  7747. window.addEventListener("blur", this._onBlur);
  7748. window.addEventListener("focus", this._onFocus);
  7749. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7750. // Context lost
  7751. if (!this._doNotHandleContextLost) {
  7752. this._onContextLost = function (evt) {
  7753. evt.preventDefault();
  7754. _this._contextWasLost = true;
  7755. BABYLON.Tools.Warn("WebGL context lost.");
  7756. _this.onContextLostObservable.notifyObservers(_this);
  7757. };
  7758. this._onContextRestored = function (evt) {
  7759. // Adding a timeout to avoid race condition at browser level
  7760. setTimeout(function () {
  7761. // Rebuild gl context
  7762. _this._initGLContext();
  7763. // Rebuild effects
  7764. _this._rebuildEffects();
  7765. // Rebuild textures
  7766. _this._rebuildInternalTextures();
  7767. // Rebuild buffers
  7768. _this._rebuildBuffers();
  7769. // Cache
  7770. _this.wipeCaches(true);
  7771. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7772. _this.onContextRestoredObservable.notifyObservers(_this);
  7773. _this._contextWasLost = false;
  7774. }, 0);
  7775. };
  7776. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7777. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7778. }
  7779. }
  7780. else {
  7781. this._gl = canvasOrContext;
  7782. this._renderingCanvas = this._gl.canvas;
  7783. if (this._gl.renderbufferStorageMultisample) {
  7784. this._webGLVersion = 2.0;
  7785. }
  7786. options.stencil = this._gl.getContextAttributes().stencil;
  7787. }
  7788. // Viewport
  7789. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7790. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7791. this.resize();
  7792. this._isStencilEnable = options.stencil;
  7793. this._initGLContext();
  7794. if (canvas) {
  7795. // Fullscreen
  7796. this._onFullscreenChange = function () {
  7797. if (document.fullscreen !== undefined) {
  7798. _this.isFullscreen = document.fullscreen;
  7799. }
  7800. else if (document.mozFullScreen !== undefined) {
  7801. _this.isFullscreen = document.mozFullScreen;
  7802. }
  7803. else if (document.webkitIsFullScreen !== undefined) {
  7804. _this.isFullscreen = document.webkitIsFullScreen;
  7805. }
  7806. else if (document.msIsFullScreen !== undefined) {
  7807. _this.isFullscreen = document.msIsFullScreen;
  7808. }
  7809. // Pointer lock
  7810. if (_this.isFullscreen && _this._pointerLockRequested) {
  7811. canvas.requestPointerLock = canvas.requestPointerLock ||
  7812. canvas.msRequestPointerLock ||
  7813. canvas.mozRequestPointerLock ||
  7814. canvas.webkitRequestPointerLock;
  7815. if (canvas.requestPointerLock) {
  7816. canvas.requestPointerLock();
  7817. }
  7818. }
  7819. };
  7820. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7821. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7822. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7823. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7824. // Pointer lock
  7825. this._onPointerLockChange = function () {
  7826. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7827. document.webkitPointerLockElement === canvas ||
  7828. document.msPointerLockElement === canvas ||
  7829. document.pointerLockElement === canvas);
  7830. };
  7831. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7832. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7833. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7834. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7835. this._onVRDisplayPointerRestricted = function () {
  7836. _this._vrExclusivePointerMode = true;
  7837. canvas.requestPointerLock();
  7838. };
  7839. this._onVRDisplayPointerUnrestricted = function () {
  7840. _this._vrExclusivePointerMode = false;
  7841. document.exitPointerLock();
  7842. };
  7843. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7844. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7845. }
  7846. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7847. Engine.audioEngine = new BABYLON.AudioEngine();
  7848. }
  7849. // Prepare buffer pointers
  7850. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7851. this._currentBufferPointers[i] = new BufferPointer();
  7852. }
  7853. // Load WebVR Devices
  7854. if (options.autoEnableWebVR) {
  7855. this.initWebVR();
  7856. }
  7857. // Detect if we are running on a faulty buggy OS.
  7858. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7859. // Detect if we are running on a faulty buggy desktop OS.
  7860. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7861. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7862. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7863. }
  7864. Object.defineProperty(Engine, "LastCreatedEngine", {
  7865. get: function () {
  7866. if (Engine.Instances.length === 0) {
  7867. return null;
  7868. }
  7869. return Engine.Instances[Engine.Instances.length - 1];
  7870. },
  7871. enumerable: true,
  7872. configurable: true
  7873. });
  7874. Object.defineProperty(Engine, "LastCreatedScene", {
  7875. get: function () {
  7876. var lastCreatedEngine = Engine.LastCreatedEngine;
  7877. if (!lastCreatedEngine) {
  7878. return null;
  7879. }
  7880. if (lastCreatedEngine.scenes.length === 0) {
  7881. return null;
  7882. }
  7883. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7884. },
  7885. enumerable: true,
  7886. configurable: true
  7887. });
  7888. /**
  7889. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7890. */
  7891. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7892. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7893. var engine = Engine.Instances[engineIndex];
  7894. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7895. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7896. }
  7897. }
  7898. };
  7899. Object.defineProperty(Engine, "NEVER", {
  7900. get: function () {
  7901. return Engine._NEVER;
  7902. },
  7903. enumerable: true,
  7904. configurable: true
  7905. });
  7906. Object.defineProperty(Engine, "ALWAYS", {
  7907. get: function () {
  7908. return Engine._ALWAYS;
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. Object.defineProperty(Engine, "LESS", {
  7914. get: function () {
  7915. return Engine._LESS;
  7916. },
  7917. enumerable: true,
  7918. configurable: true
  7919. });
  7920. Object.defineProperty(Engine, "EQUAL", {
  7921. get: function () {
  7922. return Engine._EQUAL;
  7923. },
  7924. enumerable: true,
  7925. configurable: true
  7926. });
  7927. Object.defineProperty(Engine, "LEQUAL", {
  7928. get: function () {
  7929. return Engine._LEQUAL;
  7930. },
  7931. enumerable: true,
  7932. configurable: true
  7933. });
  7934. Object.defineProperty(Engine, "GREATER", {
  7935. get: function () {
  7936. return Engine._GREATER;
  7937. },
  7938. enumerable: true,
  7939. configurable: true
  7940. });
  7941. Object.defineProperty(Engine, "GEQUAL", {
  7942. get: function () {
  7943. return Engine._GEQUAL;
  7944. },
  7945. enumerable: true,
  7946. configurable: true
  7947. });
  7948. Object.defineProperty(Engine, "NOTEQUAL", {
  7949. get: function () {
  7950. return Engine._NOTEQUAL;
  7951. },
  7952. enumerable: true,
  7953. configurable: true
  7954. });
  7955. Object.defineProperty(Engine, "KEEP", {
  7956. get: function () {
  7957. return Engine._KEEP;
  7958. },
  7959. enumerable: true,
  7960. configurable: true
  7961. });
  7962. Object.defineProperty(Engine, "REPLACE", {
  7963. get: function () {
  7964. return Engine._REPLACE;
  7965. },
  7966. enumerable: true,
  7967. configurable: true
  7968. });
  7969. Object.defineProperty(Engine, "INCR", {
  7970. get: function () {
  7971. return Engine._INCR;
  7972. },
  7973. enumerable: true,
  7974. configurable: true
  7975. });
  7976. Object.defineProperty(Engine, "DECR", {
  7977. get: function () {
  7978. return Engine._DECR;
  7979. },
  7980. enumerable: true,
  7981. configurable: true
  7982. });
  7983. Object.defineProperty(Engine, "INVERT", {
  7984. get: function () {
  7985. return Engine._INVERT;
  7986. },
  7987. enumerable: true,
  7988. configurable: true
  7989. });
  7990. Object.defineProperty(Engine, "INCR_WRAP", {
  7991. get: function () {
  7992. return Engine._INCR_WRAP;
  7993. },
  7994. enumerable: true,
  7995. configurable: true
  7996. });
  7997. Object.defineProperty(Engine, "DECR_WRAP", {
  7998. get: function () {
  7999. return Engine._DECR_WRAP;
  8000. },
  8001. enumerable: true,
  8002. configurable: true
  8003. });
  8004. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8005. get: function () {
  8006. return Engine._ALPHA_DISABLE;
  8007. },
  8008. enumerable: true,
  8009. configurable: true
  8010. });
  8011. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8012. get: function () {
  8013. return Engine._ALPHA_ONEONE;
  8014. },
  8015. enumerable: true,
  8016. configurable: true
  8017. });
  8018. Object.defineProperty(Engine, "ALPHA_ADD", {
  8019. get: function () {
  8020. return Engine._ALPHA_ADD;
  8021. },
  8022. enumerable: true,
  8023. configurable: true
  8024. });
  8025. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8026. get: function () {
  8027. return Engine._ALPHA_COMBINE;
  8028. },
  8029. enumerable: true,
  8030. configurable: true
  8031. });
  8032. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8033. get: function () {
  8034. return Engine._ALPHA_SUBTRACT;
  8035. },
  8036. enumerable: true,
  8037. configurable: true
  8038. });
  8039. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8040. get: function () {
  8041. return Engine._ALPHA_MULTIPLY;
  8042. },
  8043. enumerable: true,
  8044. configurable: true
  8045. });
  8046. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8047. get: function () {
  8048. return Engine._ALPHA_MAXIMIZED;
  8049. },
  8050. enumerable: true,
  8051. configurable: true
  8052. });
  8053. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8054. get: function () {
  8055. return Engine._ALPHA_PREMULTIPLIED;
  8056. },
  8057. enumerable: true,
  8058. configurable: true
  8059. });
  8060. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8061. get: function () {
  8062. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8063. },
  8064. enumerable: true,
  8065. configurable: true
  8066. });
  8067. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8068. get: function () {
  8069. return Engine._ALPHA_INTERPOLATE;
  8070. },
  8071. enumerable: true,
  8072. configurable: true
  8073. });
  8074. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8075. get: function () {
  8076. return Engine._ALPHA_SCREENMODE;
  8077. },
  8078. enumerable: true,
  8079. configurable: true
  8080. });
  8081. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8082. get: function () {
  8083. return Engine._DELAYLOADSTATE_NONE;
  8084. },
  8085. enumerable: true,
  8086. configurable: true
  8087. });
  8088. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8089. get: function () {
  8090. return Engine._DELAYLOADSTATE_LOADED;
  8091. },
  8092. enumerable: true,
  8093. configurable: true
  8094. });
  8095. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8096. get: function () {
  8097. return Engine._DELAYLOADSTATE_LOADING;
  8098. },
  8099. enumerable: true,
  8100. configurable: true
  8101. });
  8102. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8103. get: function () {
  8104. return Engine._DELAYLOADSTATE_NOTLOADED;
  8105. },
  8106. enumerable: true,
  8107. configurable: true
  8108. });
  8109. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8110. get: function () {
  8111. return Engine._TEXTUREFORMAT_ALPHA;
  8112. },
  8113. enumerable: true,
  8114. configurable: true
  8115. });
  8116. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8117. get: function () {
  8118. return Engine._TEXTUREFORMAT_LUMINANCE;
  8119. },
  8120. enumerable: true,
  8121. configurable: true
  8122. });
  8123. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8124. get: function () {
  8125. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8126. },
  8127. enumerable: true,
  8128. configurable: true
  8129. });
  8130. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8131. get: function () {
  8132. return Engine._TEXTUREFORMAT_RGB;
  8133. },
  8134. enumerable: true,
  8135. configurable: true
  8136. });
  8137. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8138. get: function () {
  8139. return Engine._TEXTUREFORMAT_RGBA;
  8140. },
  8141. enumerable: true,
  8142. configurable: true
  8143. });
  8144. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8145. get: function () {
  8146. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8147. },
  8148. enumerable: true,
  8149. configurable: true
  8150. });
  8151. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8152. get: function () {
  8153. return Engine._TEXTURETYPE_FLOAT;
  8154. },
  8155. enumerable: true,
  8156. configurable: true
  8157. });
  8158. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8159. get: function () {
  8160. return Engine._TEXTURETYPE_HALF_FLOAT;
  8161. },
  8162. enumerable: true,
  8163. configurable: true
  8164. });
  8165. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8166. get: function () {
  8167. return Engine._SCALEMODE_FLOOR;
  8168. },
  8169. enumerable: true,
  8170. configurable: true
  8171. });
  8172. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8173. get: function () {
  8174. return Engine._SCALEMODE_NEAREST;
  8175. },
  8176. enumerable: true,
  8177. configurable: true
  8178. });
  8179. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8180. get: function () {
  8181. return Engine._SCALEMODE_CEILING;
  8182. },
  8183. enumerable: true,
  8184. configurable: true
  8185. });
  8186. Object.defineProperty(Engine, "Version", {
  8187. get: function () {
  8188. return "3.1-alpha";
  8189. },
  8190. enumerable: true,
  8191. configurable: true
  8192. });
  8193. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8194. get: function () {
  8195. return this._vrExclusivePointerMode;
  8196. },
  8197. enumerable: true,
  8198. configurable: true
  8199. });
  8200. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8201. get: function () {
  8202. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8203. },
  8204. enumerable: true,
  8205. configurable: true
  8206. });
  8207. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8208. get: function () {
  8209. return this._webGLVersion < 2 || this.forcePOTTextures;
  8210. },
  8211. enumerable: true,
  8212. configurable: true
  8213. });
  8214. Object.defineProperty(Engine.prototype, "badOS", {
  8215. get: function () {
  8216. return this._badOS;
  8217. },
  8218. enumerable: true,
  8219. configurable: true
  8220. });
  8221. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8222. get: function () {
  8223. return this._badDesktopOS;
  8224. },
  8225. enumerable: true,
  8226. configurable: true
  8227. });
  8228. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8229. get: function () {
  8230. return this._performanceMonitor;
  8231. },
  8232. enumerable: true,
  8233. configurable: true
  8234. });
  8235. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8236. get: function () {
  8237. return this._texturesSupported;
  8238. },
  8239. enumerable: true,
  8240. configurable: true
  8241. });
  8242. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8243. get: function () {
  8244. return this._textureFormatInUse;
  8245. },
  8246. enumerable: true,
  8247. configurable: true
  8248. });
  8249. Object.defineProperty(Engine.prototype, "currentViewport", {
  8250. get: function () {
  8251. return this._cachedViewport;
  8252. },
  8253. enumerable: true,
  8254. configurable: true
  8255. });
  8256. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8257. // Empty texture
  8258. get: function () {
  8259. if (!this._emptyTexture) {
  8260. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8261. }
  8262. return this._emptyTexture;
  8263. },
  8264. enumerable: true,
  8265. configurable: true
  8266. });
  8267. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8268. get: function () {
  8269. if (!this._emptyCubeTexture) {
  8270. var faceData = new Uint8Array(4);
  8271. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8272. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8273. }
  8274. return this._emptyCubeTexture;
  8275. },
  8276. enumerable: true,
  8277. configurable: true
  8278. });
  8279. Engine.prototype._rebuildInternalTextures = function () {
  8280. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8281. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8282. var internalTexture = currentState_1[_i];
  8283. internalTexture._rebuild();
  8284. }
  8285. };
  8286. Engine.prototype._rebuildEffects = function () {
  8287. for (var key in this._compiledEffects) {
  8288. var effect = this._compiledEffects[key];
  8289. effect._prepareEffect();
  8290. }
  8291. BABYLON.Effect.ResetCache();
  8292. };
  8293. Engine.prototype._rebuildBuffers = function () {
  8294. // Index / Vertex
  8295. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8296. var scene = _a[_i];
  8297. scene.resetCachedMaterial();
  8298. scene._rebuildGeometries();
  8299. scene._rebuildTextures();
  8300. }
  8301. // Uniforms
  8302. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8303. var uniformBuffer = _c[_b];
  8304. uniformBuffer._rebuild();
  8305. }
  8306. };
  8307. Engine.prototype._initGLContext = function () {
  8308. // Caps
  8309. this._caps = new EngineCapabilities();
  8310. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8311. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8312. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8313. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8314. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8315. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8316. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8317. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8318. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8319. // Infos
  8320. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8321. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8322. if (rendererInfo != null) {
  8323. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8324. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8325. }
  8326. if (!this._glVendor) {
  8327. this._glVendor = "Unknown vendor";
  8328. }
  8329. if (!this._glRenderer) {
  8330. this._glRenderer = "Unknown renderer";
  8331. }
  8332. // Constants
  8333. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8334. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8335. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8336. this._gl.DEPTH24_STENCIL8 = 35056;
  8337. // Extensions
  8338. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8339. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8340. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8341. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8342. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8343. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8344. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8345. 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');
  8346. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8347. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8348. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8349. this._caps.highPrecisionShaderSupported = true;
  8350. // Checks if some of the format renders first to allow the use of webgl inspector.
  8351. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8352. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8353. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8354. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8355. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8356. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8357. if (this._webGLVersion > 1) {
  8358. this._gl.HALF_FLOAT_OES = 0x140B;
  8359. }
  8360. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8361. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8362. // Draw buffers
  8363. if (this._webGLVersion > 1) {
  8364. this._caps.drawBuffersExtension = true;
  8365. }
  8366. else {
  8367. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8368. if (drawBuffersExtension !== null) {
  8369. this._caps.drawBuffersExtension = true;
  8370. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8371. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8372. for (var i = 0; i < 16; i++) {
  8373. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8374. }
  8375. }
  8376. else {
  8377. this._caps.drawBuffersExtension = false;
  8378. }
  8379. }
  8380. // Depth Texture
  8381. if (this._webGLVersion > 1) {
  8382. this._caps.depthTextureExtension = true;
  8383. }
  8384. else {
  8385. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8386. if (depthTextureExtension != null) {
  8387. this._caps.depthTextureExtension = true;
  8388. }
  8389. }
  8390. // Vertex array object
  8391. if (this._webGLVersion > 1) {
  8392. this._caps.vertexArrayObject = true;
  8393. }
  8394. else {
  8395. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8396. if (vertexArrayObjectExtension != null) {
  8397. this._caps.vertexArrayObject = true;
  8398. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8399. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8400. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8401. }
  8402. else {
  8403. this._caps.vertexArrayObject = false;
  8404. }
  8405. }
  8406. // Instances count
  8407. if (this._webGLVersion > 1) {
  8408. this._caps.instancedArrays = true;
  8409. }
  8410. else {
  8411. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8412. if (instanceExtension != null) {
  8413. this._caps.instancedArrays = true;
  8414. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8415. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8416. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8417. }
  8418. else {
  8419. this._caps.instancedArrays = false;
  8420. }
  8421. }
  8422. // Intelligently add supported compressed formats in order to check for.
  8423. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8424. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8425. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8426. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8427. if (this._caps.astc)
  8428. this.texturesSupported.push('-astc.ktx');
  8429. if (this._caps.s3tc)
  8430. this.texturesSupported.push('-dxt.ktx');
  8431. if (this._caps.pvrtc)
  8432. this.texturesSupported.push('-pvrtc.ktx');
  8433. if (this._caps.etc2)
  8434. this.texturesSupported.push('-etc2.ktx');
  8435. if (this._caps.etc1)
  8436. this.texturesSupported.push('-etc1.ktx');
  8437. if (this._gl.getShaderPrecisionFormat) {
  8438. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8439. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8440. }
  8441. // Depth buffer
  8442. this.setDepthBuffer(true);
  8443. this.setDepthFunctionToLessOrEqual();
  8444. this.setDepthWrite(true);
  8445. };
  8446. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8447. get: function () {
  8448. return this._webGLVersion;
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8454. /**
  8455. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8456. */
  8457. get: function () {
  8458. return this._isStencilEnable;
  8459. },
  8460. enumerable: true,
  8461. configurable: true
  8462. });
  8463. Engine.prototype._prepareWorkingCanvas = function () {
  8464. if (this._workingCanvas) {
  8465. return;
  8466. }
  8467. this._workingCanvas = document.createElement("canvas");
  8468. this._workingContext = this._workingCanvas.getContext("2d");
  8469. };
  8470. Engine.prototype.resetTextureCache = function () {
  8471. for (var key in this._activeTexturesCache) {
  8472. this._activeTexturesCache[key] = null;
  8473. }
  8474. };
  8475. Engine.prototype.isDeterministicLockStep = function () {
  8476. return this._deterministicLockstep;
  8477. };
  8478. Engine.prototype.getLockstepMaxSteps = function () {
  8479. return this._lockstepMaxSteps;
  8480. };
  8481. Engine.prototype.getGlInfo = function () {
  8482. return {
  8483. vendor: this._glVendor,
  8484. renderer: this._glRenderer,
  8485. version: this._glVersion
  8486. };
  8487. };
  8488. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8489. if (useScreen === void 0) { useScreen = false; }
  8490. var viewport = camera.viewport;
  8491. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8492. };
  8493. Engine.prototype.getRenderWidth = function (useScreen) {
  8494. if (useScreen === void 0) { useScreen = false; }
  8495. if (!useScreen && this._currentRenderTarget) {
  8496. return this._currentRenderTarget.width;
  8497. }
  8498. return this._gl.drawingBufferWidth;
  8499. };
  8500. Engine.prototype.getRenderHeight = function (useScreen) {
  8501. if (useScreen === void 0) { useScreen = false; }
  8502. if (!useScreen && this._currentRenderTarget) {
  8503. return this._currentRenderTarget.height;
  8504. }
  8505. return this._gl.drawingBufferHeight;
  8506. };
  8507. Engine.prototype.getRenderingCanvas = function () {
  8508. return this._renderingCanvas;
  8509. };
  8510. Engine.prototype.getRenderingCanvasClientRect = function () {
  8511. return this._renderingCanvas.getBoundingClientRect();
  8512. };
  8513. Engine.prototype.setHardwareScalingLevel = function (level) {
  8514. this._hardwareScalingLevel = level;
  8515. this.resize();
  8516. };
  8517. Engine.prototype.getHardwareScalingLevel = function () {
  8518. return this._hardwareScalingLevel;
  8519. };
  8520. Engine.prototype.getLoadedTexturesCache = function () {
  8521. return this._internalTexturesCache;
  8522. };
  8523. Engine.prototype.getCaps = function () {
  8524. return this._caps;
  8525. };
  8526. Object.defineProperty(Engine.prototype, "drawCalls", {
  8527. /** The number of draw calls submitted last frame */
  8528. get: function () {
  8529. return this._drawCalls.current;
  8530. },
  8531. enumerable: true,
  8532. configurable: true
  8533. });
  8534. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8535. get: function () {
  8536. return this._drawCalls;
  8537. },
  8538. enumerable: true,
  8539. configurable: true
  8540. });
  8541. Engine.prototype.getDepthFunction = function () {
  8542. return this._depthCullingState.depthFunc;
  8543. };
  8544. Engine.prototype.setDepthFunction = function (depthFunc) {
  8545. this._depthCullingState.depthFunc = depthFunc;
  8546. };
  8547. Engine.prototype.setDepthFunctionToGreater = function () {
  8548. this._depthCullingState.depthFunc = this._gl.GREATER;
  8549. };
  8550. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8551. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8552. };
  8553. Engine.prototype.setDepthFunctionToLess = function () {
  8554. this._depthCullingState.depthFunc = this._gl.LESS;
  8555. };
  8556. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8557. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8558. };
  8559. Engine.prototype.getStencilBuffer = function () {
  8560. return this._stencilState.stencilTest;
  8561. };
  8562. Engine.prototype.setStencilBuffer = function (enable) {
  8563. this._stencilState.stencilTest = enable;
  8564. };
  8565. Engine.prototype.getStencilMask = function () {
  8566. return this._stencilState.stencilMask;
  8567. };
  8568. Engine.prototype.setStencilMask = function (mask) {
  8569. this._stencilState.stencilMask = mask;
  8570. };
  8571. Engine.prototype.getStencilFunction = function () {
  8572. return this._stencilState.stencilFunc;
  8573. };
  8574. Engine.prototype.getStencilFunctionReference = function () {
  8575. return this._stencilState.stencilFuncRef;
  8576. };
  8577. Engine.prototype.getStencilFunctionMask = function () {
  8578. return this._stencilState.stencilFuncMask;
  8579. };
  8580. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8581. this._stencilState.stencilFunc = stencilFunc;
  8582. };
  8583. Engine.prototype.setStencilFunctionReference = function (reference) {
  8584. this._stencilState.stencilFuncRef = reference;
  8585. };
  8586. Engine.prototype.setStencilFunctionMask = function (mask) {
  8587. this._stencilState.stencilFuncMask = mask;
  8588. };
  8589. Engine.prototype.getStencilOperationFail = function () {
  8590. return this._stencilState.stencilOpStencilFail;
  8591. };
  8592. Engine.prototype.getStencilOperationDepthFail = function () {
  8593. return this._stencilState.stencilOpDepthFail;
  8594. };
  8595. Engine.prototype.getStencilOperationPass = function () {
  8596. return this._stencilState.stencilOpStencilDepthPass;
  8597. };
  8598. Engine.prototype.setStencilOperationFail = function (operation) {
  8599. this._stencilState.stencilOpStencilFail = operation;
  8600. };
  8601. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8602. this._stencilState.stencilOpDepthFail = operation;
  8603. };
  8604. Engine.prototype.setStencilOperationPass = function (operation) {
  8605. this._stencilState.stencilOpStencilDepthPass = operation;
  8606. };
  8607. Engine.prototype.setDitheringState = function (value) {
  8608. if (value) {
  8609. this._gl.enable(this._gl.DITHER);
  8610. }
  8611. else {
  8612. this._gl.disable(this._gl.DITHER);
  8613. }
  8614. };
  8615. /**
  8616. * stop executing a render loop function and remove it from the execution array
  8617. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8618. */
  8619. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8620. if (!renderFunction) {
  8621. this._activeRenderLoops = [];
  8622. return;
  8623. }
  8624. var index = this._activeRenderLoops.indexOf(renderFunction);
  8625. if (index >= 0) {
  8626. this._activeRenderLoops.splice(index, 1);
  8627. }
  8628. };
  8629. Engine.prototype._renderLoop = function () {
  8630. if (!this._contextWasLost) {
  8631. var shouldRender = true;
  8632. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8633. shouldRender = false;
  8634. }
  8635. if (shouldRender) {
  8636. // Start new frame
  8637. this.beginFrame();
  8638. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8639. var renderFunction = this._activeRenderLoops[index];
  8640. renderFunction();
  8641. }
  8642. // Present
  8643. this.endFrame();
  8644. }
  8645. }
  8646. if (this._activeRenderLoops.length > 0) {
  8647. // Register new frame
  8648. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8649. }
  8650. else {
  8651. this._renderingQueueLaunched = false;
  8652. }
  8653. };
  8654. /**
  8655. * Register and execute a render loop. The engine can have more than one render function.
  8656. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8657. * @example
  8658. * engine.runRenderLoop(function () {
  8659. * scene.render()
  8660. * })
  8661. */
  8662. Engine.prototype.runRenderLoop = function (renderFunction) {
  8663. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8664. return;
  8665. }
  8666. this._activeRenderLoops.push(renderFunction);
  8667. if (!this._renderingQueueLaunched) {
  8668. this._renderingQueueLaunched = true;
  8669. this._bindedRenderFunction = this._renderLoop.bind(this);
  8670. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8671. }
  8672. };
  8673. /**
  8674. * Toggle full screen mode.
  8675. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8676. * @param {any} options - an options object to be sent to the requestFullscreen function
  8677. */
  8678. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8679. if (this.isFullscreen) {
  8680. BABYLON.Tools.ExitFullscreen();
  8681. }
  8682. else {
  8683. this._pointerLockRequested = requestPointerLock;
  8684. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8685. }
  8686. };
  8687. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8688. if (stencil === void 0) { stencil = false; }
  8689. this.applyStates();
  8690. var mode = 0;
  8691. if (backBuffer && color) {
  8692. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8693. mode |= this._gl.COLOR_BUFFER_BIT;
  8694. }
  8695. if (depth) {
  8696. this._gl.clearDepth(1.0);
  8697. mode |= this._gl.DEPTH_BUFFER_BIT;
  8698. }
  8699. if (stencil) {
  8700. this._gl.clearStencil(0);
  8701. mode |= this._gl.STENCIL_BUFFER_BIT;
  8702. }
  8703. this._gl.clear(mode);
  8704. };
  8705. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8706. var gl = this._gl;
  8707. // Save state
  8708. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8709. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8710. // Change state
  8711. gl.enable(gl.SCISSOR_TEST);
  8712. gl.scissor(x, y, width, height);
  8713. // Clear
  8714. this.clear(clearColor, true, true, true);
  8715. // Restore state
  8716. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8717. if (curScissor === true) {
  8718. gl.enable(gl.SCISSOR_TEST);
  8719. }
  8720. else {
  8721. gl.disable(gl.SCISSOR_TEST);
  8722. }
  8723. };
  8724. /**
  8725. * Set the WebGL's viewport
  8726. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8727. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8728. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8729. */
  8730. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8731. var width = requiredWidth || this.getRenderWidth();
  8732. var height = requiredHeight || this.getRenderHeight();
  8733. var x = viewport.x || 0;
  8734. var y = viewport.y || 0;
  8735. this._cachedViewport = viewport;
  8736. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8737. };
  8738. /**
  8739. * Directly set the WebGL Viewport
  8740. * The x, y, width & height are directly passed to the WebGL call
  8741. * @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.
  8742. */
  8743. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8744. var currentViewport = this._cachedViewport;
  8745. this._cachedViewport = null;
  8746. this._gl.viewport(x, y, width, height);
  8747. return currentViewport;
  8748. };
  8749. Engine.prototype.beginFrame = function () {
  8750. this._measureFps();
  8751. };
  8752. Engine.prototype.endFrame = function () {
  8753. //force a flush in case we are using a bad OS.
  8754. if (this._badOS) {
  8755. this.flushFramebuffer();
  8756. }
  8757. //submit frame to the vr device, if enabled
  8758. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8759. this._vrDisplayEnabled.submitFrame();
  8760. }
  8761. };
  8762. /**
  8763. * resize the view according to the canvas' size.
  8764. * @example
  8765. * window.addEventListener("resize", function () {
  8766. * engine.resize();
  8767. * });
  8768. */
  8769. Engine.prototype.resize = function () {
  8770. // We're not resizing the size of the canvas while in VR mode & presenting
  8771. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8772. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8773. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8774. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8775. }
  8776. };
  8777. /**
  8778. * force a specific size of the canvas
  8779. * @param {number} width - the new canvas' width
  8780. * @param {number} height - the new canvas' height
  8781. */
  8782. Engine.prototype.setSize = function (width, height) {
  8783. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8784. return;
  8785. }
  8786. this._renderingCanvas.width = width;
  8787. this._renderingCanvas.height = height;
  8788. for (var index = 0; index < this.scenes.length; index++) {
  8789. var scene = this.scenes[index];
  8790. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8791. var cam = scene.cameras[camIndex];
  8792. cam._currentRenderId = 0;
  8793. }
  8794. }
  8795. if (this.onResizeObservable.hasObservers) {
  8796. this.onResizeObservable.notifyObservers(this);
  8797. }
  8798. };
  8799. //WebVR functions
  8800. Engine.prototype.isVRDevicePresent = function (callback) {
  8801. this.getVRDevice(null, function (device) {
  8802. callback(device !== null);
  8803. });
  8804. };
  8805. Engine.prototype.getVRDevice = function (name, callback) {
  8806. if (!this.vrDisplaysPromise) {
  8807. callback(null);
  8808. return;
  8809. }
  8810. this.vrDisplaysPromise.then(function (devices) {
  8811. if (devices.length > 0) {
  8812. if (name) {
  8813. var found = devices.some(function (device) {
  8814. if (device.displayName === name) {
  8815. callback(device);
  8816. return true;
  8817. }
  8818. else {
  8819. return false;
  8820. }
  8821. });
  8822. if (!found) {
  8823. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8824. callback(devices[0]);
  8825. }
  8826. }
  8827. else {
  8828. //choose the first one
  8829. callback(devices[0]);
  8830. }
  8831. }
  8832. else {
  8833. BABYLON.Tools.Error("No WebVR devices found!");
  8834. callback(null);
  8835. }
  8836. });
  8837. };
  8838. Engine.prototype.initWebVR = function () {
  8839. if (!this.vrDisplaysPromise) {
  8840. this._getVRDisplays();
  8841. }
  8842. };
  8843. Engine.prototype.enableVR = function (vrDevice) {
  8844. this._vrDisplayEnabled = vrDevice;
  8845. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8846. };
  8847. Engine.prototype.disableVR = function () {
  8848. if (this._vrDisplayEnabled) {
  8849. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8850. }
  8851. };
  8852. Engine.prototype._getVRDisplays = function () {
  8853. var _this = this;
  8854. var getWebVRDevices = function (devices) {
  8855. _this._vrDisplays = devices.filter(function (device) {
  8856. return device instanceof VRDisplay;
  8857. });
  8858. return _this._vrDisplays;
  8859. };
  8860. if (navigator.getVRDisplays) {
  8861. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8862. }
  8863. };
  8864. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8865. if (this._currentRenderTarget) {
  8866. this.unBindFramebuffer(this._currentRenderTarget);
  8867. }
  8868. this._currentRenderTarget = texture;
  8869. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8870. var gl = this._gl;
  8871. if (texture.isCube) {
  8872. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8873. }
  8874. if (this._cachedViewport && !forceFullscreenViewport) {
  8875. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8876. }
  8877. else {
  8878. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8879. }
  8880. this.wipeCaches();
  8881. };
  8882. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8883. if (this._currentFramebuffer !== framebuffer) {
  8884. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8885. this._currentFramebuffer = framebuffer;
  8886. }
  8887. };
  8888. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8889. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8890. this._currentRenderTarget = null;
  8891. // If MSAA, we need to bitblt back to main texture
  8892. var gl = this._gl;
  8893. if (texture._MSAAFramebuffer) {
  8894. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8895. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8896. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8897. }
  8898. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8899. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8900. gl.generateMipmap(gl.TEXTURE_2D);
  8901. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8902. }
  8903. if (onBeforeUnbind) {
  8904. if (texture._MSAAFramebuffer) {
  8905. // Bind the correct framebuffer
  8906. this.bindUnboundFramebuffer(texture._framebuffer);
  8907. }
  8908. onBeforeUnbind();
  8909. }
  8910. this.bindUnboundFramebuffer(null);
  8911. };
  8912. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8913. if (texture.generateMipMaps) {
  8914. var gl = this._gl;
  8915. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8916. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8917. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8918. }
  8919. };
  8920. Engine.prototype.flushFramebuffer = function () {
  8921. this._gl.flush();
  8922. };
  8923. Engine.prototype.restoreDefaultFramebuffer = function () {
  8924. if (this._currentRenderTarget) {
  8925. this.unBindFramebuffer(this._currentRenderTarget);
  8926. }
  8927. else {
  8928. this.bindUnboundFramebuffer(null);
  8929. }
  8930. if (this._cachedViewport) {
  8931. this.setViewport(this._cachedViewport);
  8932. }
  8933. this.wipeCaches();
  8934. };
  8935. // UBOs
  8936. Engine.prototype.createUniformBuffer = function (elements) {
  8937. var ubo = this._gl.createBuffer();
  8938. this.bindUniformBuffer(ubo);
  8939. if (elements instanceof Float32Array) {
  8940. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8941. }
  8942. else {
  8943. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8944. }
  8945. this.bindUniformBuffer(null);
  8946. ubo.references = 1;
  8947. return ubo;
  8948. };
  8949. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8950. var ubo = this._gl.createBuffer();
  8951. this.bindUniformBuffer(ubo);
  8952. if (elements instanceof Float32Array) {
  8953. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8954. }
  8955. else {
  8956. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8957. }
  8958. this.bindUniformBuffer(null);
  8959. ubo.references = 1;
  8960. return ubo;
  8961. };
  8962. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8963. this.bindUniformBuffer(uniformBuffer);
  8964. if (offset === undefined) {
  8965. offset = 0;
  8966. }
  8967. if (count === undefined) {
  8968. if (elements instanceof Float32Array) {
  8969. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8970. }
  8971. else {
  8972. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8973. }
  8974. }
  8975. else {
  8976. if (elements instanceof Float32Array) {
  8977. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8978. }
  8979. else {
  8980. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8981. }
  8982. }
  8983. this.bindUniformBuffer(null);
  8984. };
  8985. // VBOs
  8986. Engine.prototype._resetVertexBufferBinding = function () {
  8987. this.bindArrayBuffer(null);
  8988. this._cachedVertexBuffers = null;
  8989. };
  8990. Engine.prototype.createVertexBuffer = function (vertices) {
  8991. var vbo = this._gl.createBuffer();
  8992. this.bindArrayBuffer(vbo);
  8993. if (vertices instanceof Float32Array) {
  8994. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8995. }
  8996. else {
  8997. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8998. }
  8999. this._resetVertexBufferBinding();
  9000. vbo.references = 1;
  9001. return vbo;
  9002. };
  9003. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9004. var vbo = this._gl.createBuffer();
  9005. this.bindArrayBuffer(vbo);
  9006. if (vertices instanceof Float32Array) {
  9007. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9008. }
  9009. else {
  9010. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9011. }
  9012. this._resetVertexBufferBinding();
  9013. vbo.references = 1;
  9014. return vbo;
  9015. };
  9016. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9017. this.bindArrayBuffer(vertexBuffer);
  9018. if (offset === undefined) {
  9019. offset = 0;
  9020. }
  9021. if (count === undefined) {
  9022. if (vertices instanceof Float32Array) {
  9023. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9024. }
  9025. else {
  9026. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9027. }
  9028. }
  9029. else {
  9030. if (vertices instanceof Float32Array) {
  9031. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9032. }
  9033. else {
  9034. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9035. }
  9036. }
  9037. this._resetVertexBufferBinding();
  9038. };
  9039. Engine.prototype._resetIndexBufferBinding = function () {
  9040. this.bindIndexBuffer(null);
  9041. this._cachedIndexBuffer = null;
  9042. };
  9043. Engine.prototype.createIndexBuffer = function (indices) {
  9044. var vbo = this._gl.createBuffer();
  9045. this.bindIndexBuffer(vbo);
  9046. // Check for 32 bits indices
  9047. var arrayBuffer;
  9048. var need32Bits = false;
  9049. if (indices instanceof Uint16Array) {
  9050. arrayBuffer = indices;
  9051. }
  9052. else {
  9053. //check 32 bit support
  9054. if (this._caps.uintIndices) {
  9055. if (indices instanceof Uint32Array) {
  9056. arrayBuffer = indices;
  9057. need32Bits = true;
  9058. }
  9059. else {
  9060. //number[] or Int32Array, check if 32 bit is necessary
  9061. for (var index = 0; index < indices.length; index++) {
  9062. if (indices[index] > 65535) {
  9063. need32Bits = true;
  9064. break;
  9065. }
  9066. }
  9067. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9068. }
  9069. }
  9070. else {
  9071. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9072. arrayBuffer = new Uint16Array(indices);
  9073. }
  9074. }
  9075. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9076. this._resetIndexBufferBinding();
  9077. vbo.references = 1;
  9078. vbo.is32Bits = need32Bits;
  9079. return vbo;
  9080. };
  9081. Engine.prototype.bindArrayBuffer = function (buffer) {
  9082. if (!this._vaoRecordInProgress) {
  9083. this._unbindVertexArrayObject();
  9084. }
  9085. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9086. };
  9087. Engine.prototype.bindUniformBuffer = function (buffer) {
  9088. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9089. };
  9090. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9091. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9092. };
  9093. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9094. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9095. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9096. };
  9097. ;
  9098. Engine.prototype.bindIndexBuffer = function (buffer) {
  9099. if (!this._vaoRecordInProgress) {
  9100. this._unbindVertexArrayObject();
  9101. }
  9102. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9103. };
  9104. Engine.prototype.bindBuffer = function (buffer, target) {
  9105. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9106. this._gl.bindBuffer(target, buffer);
  9107. this._currentBoundBuffer[target] = buffer;
  9108. }
  9109. };
  9110. Engine.prototype.updateArrayBuffer = function (data) {
  9111. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9112. };
  9113. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9114. var pointer = this._currentBufferPointers[indx];
  9115. var changed = false;
  9116. if (!pointer.active) {
  9117. changed = true;
  9118. pointer.active = true;
  9119. pointer.index = indx;
  9120. pointer.size = size;
  9121. pointer.type = type;
  9122. pointer.normalized = normalized;
  9123. pointer.stride = stride;
  9124. pointer.offset = offset;
  9125. pointer.buffer = buffer;
  9126. }
  9127. else {
  9128. if (pointer.buffer !== buffer) {
  9129. pointer.buffer = buffer;
  9130. changed = true;
  9131. }
  9132. if (pointer.size !== size) {
  9133. pointer.size = size;
  9134. changed = true;
  9135. }
  9136. if (pointer.type !== type) {
  9137. pointer.type = type;
  9138. changed = true;
  9139. }
  9140. if (pointer.normalized !== normalized) {
  9141. pointer.normalized = normalized;
  9142. changed = true;
  9143. }
  9144. if (pointer.stride !== stride) {
  9145. pointer.stride = stride;
  9146. changed = true;
  9147. }
  9148. if (pointer.offset !== offset) {
  9149. pointer.offset = offset;
  9150. changed = true;
  9151. }
  9152. }
  9153. if (changed || this._vaoRecordInProgress) {
  9154. this.bindArrayBuffer(buffer);
  9155. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9156. }
  9157. };
  9158. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9159. if (indexBuffer == null) {
  9160. return;
  9161. }
  9162. if (this._cachedIndexBuffer !== indexBuffer) {
  9163. this._cachedIndexBuffer = indexBuffer;
  9164. this.bindIndexBuffer(indexBuffer);
  9165. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9166. }
  9167. };
  9168. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9169. var attributes = effect.getAttributesNames();
  9170. if (!this._vaoRecordInProgress) {
  9171. this._unbindVertexArrayObject();
  9172. }
  9173. this.unbindAllAttributes();
  9174. for (var index = 0; index < attributes.length; index++) {
  9175. var order = effect.getAttributeLocation(index);
  9176. if (order >= 0) {
  9177. var vertexBuffer = vertexBuffers[attributes[index]];
  9178. if (!vertexBuffer) {
  9179. continue;
  9180. }
  9181. this._gl.enableVertexAttribArray(order);
  9182. if (!this._vaoRecordInProgress) {
  9183. this._vertexAttribArraysEnabled[order] = true;
  9184. }
  9185. var buffer = vertexBuffer.getBuffer();
  9186. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9187. if (vertexBuffer.getIsInstanced()) {
  9188. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9189. if (!this._vaoRecordInProgress) {
  9190. this._currentInstanceLocations.push(order);
  9191. this._currentInstanceBuffers.push(buffer);
  9192. }
  9193. }
  9194. }
  9195. }
  9196. };
  9197. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9198. var vao = this._gl.createVertexArray();
  9199. this._vaoRecordInProgress = true;
  9200. this._gl.bindVertexArray(vao);
  9201. this._mustWipeVertexAttributes = true;
  9202. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9203. this.bindIndexBuffer(indexBuffer);
  9204. this._vaoRecordInProgress = false;
  9205. this._gl.bindVertexArray(null);
  9206. return vao;
  9207. };
  9208. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9209. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9210. this._cachedVertexArrayObject = vertexArrayObject;
  9211. this._gl.bindVertexArray(vertexArrayObject);
  9212. this._cachedVertexBuffers = null;
  9213. this._cachedIndexBuffer = null;
  9214. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9215. this._mustWipeVertexAttributes = true;
  9216. }
  9217. };
  9218. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9219. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9220. this._cachedVertexBuffers = vertexBuffer;
  9221. this._cachedEffectForVertexBuffers = effect;
  9222. var attributesCount = effect.getAttributesCount();
  9223. this._unbindVertexArrayObject();
  9224. this.unbindAllAttributes();
  9225. var offset = 0;
  9226. for (var index = 0; index < attributesCount; index++) {
  9227. if (index < vertexDeclaration.length) {
  9228. var order = effect.getAttributeLocation(index);
  9229. if (order >= 0) {
  9230. this._gl.enableVertexAttribArray(order);
  9231. this._vertexAttribArraysEnabled[order] = true;
  9232. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9233. }
  9234. offset += vertexDeclaration[index] * 4;
  9235. }
  9236. }
  9237. }
  9238. this._bindIndexBufferWithCache(indexBuffer);
  9239. };
  9240. Engine.prototype._unbindVertexArrayObject = function () {
  9241. if (!this._cachedVertexArrayObject) {
  9242. return;
  9243. }
  9244. this._cachedVertexArrayObject = null;
  9245. this._gl.bindVertexArray(null);
  9246. };
  9247. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9248. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9249. this._cachedVertexBuffers = vertexBuffers;
  9250. this._cachedEffectForVertexBuffers = effect;
  9251. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9252. }
  9253. this._bindIndexBufferWithCache(indexBuffer);
  9254. };
  9255. Engine.prototype.unbindInstanceAttributes = function () {
  9256. var boundBuffer;
  9257. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9258. var instancesBuffer = this._currentInstanceBuffers[i];
  9259. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9260. boundBuffer = instancesBuffer;
  9261. this.bindArrayBuffer(instancesBuffer);
  9262. }
  9263. var offsetLocation = this._currentInstanceLocations[i];
  9264. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9265. }
  9266. this._currentInstanceBuffers.length = 0;
  9267. this._currentInstanceLocations.length = 0;
  9268. };
  9269. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9270. this._gl.deleteVertexArray(vao);
  9271. };
  9272. Engine.prototype._releaseBuffer = function (buffer) {
  9273. buffer.references--;
  9274. if (buffer.references === 0) {
  9275. this._gl.deleteBuffer(buffer);
  9276. return true;
  9277. }
  9278. return false;
  9279. };
  9280. Engine.prototype.createInstancesBuffer = function (capacity) {
  9281. var buffer = this._gl.createBuffer();
  9282. buffer.capacity = capacity;
  9283. this.bindArrayBuffer(buffer);
  9284. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9285. return buffer;
  9286. };
  9287. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9288. this._gl.deleteBuffer(buffer);
  9289. };
  9290. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9291. this.bindArrayBuffer(instancesBuffer);
  9292. if (data) {
  9293. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9294. }
  9295. if (offsetLocations[0].index !== undefined) {
  9296. var stride = 0;
  9297. for (var i = 0; i < offsetLocations.length; i++) {
  9298. var ai = offsetLocations[i];
  9299. stride += ai.attributeSize * 4;
  9300. }
  9301. for (var i = 0; i < offsetLocations.length; i++) {
  9302. var ai = offsetLocations[i];
  9303. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9304. this._gl.enableVertexAttribArray(ai.index);
  9305. this._vertexAttribArraysEnabled[ai.index] = true;
  9306. }
  9307. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9308. this._gl.vertexAttribDivisor(ai.index, 1);
  9309. this._currentInstanceLocations.push(ai.index);
  9310. this._currentInstanceBuffers.push(instancesBuffer);
  9311. }
  9312. }
  9313. else {
  9314. for (var index = 0; index < 4; index++) {
  9315. var offsetLocation = offsetLocations[index];
  9316. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9317. this._gl.enableVertexAttribArray(offsetLocation);
  9318. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9319. }
  9320. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9321. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9322. this._currentInstanceLocations.push(offsetLocation);
  9323. this._currentInstanceBuffers.push(instancesBuffer);
  9324. }
  9325. }
  9326. };
  9327. Engine.prototype.applyStates = function () {
  9328. this._depthCullingState.apply(this._gl);
  9329. this._stencilState.apply(this._gl);
  9330. this._alphaState.apply(this._gl);
  9331. };
  9332. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9333. // Apply states
  9334. this.applyStates();
  9335. this._drawCalls.addCount(1, false);
  9336. // Render
  9337. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9338. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9339. if (instancesCount) {
  9340. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9341. return;
  9342. }
  9343. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9344. };
  9345. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9346. // Apply states
  9347. this.applyStates();
  9348. this._drawCalls.addCount(1, false);
  9349. if (instancesCount) {
  9350. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9351. return;
  9352. }
  9353. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9354. };
  9355. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9356. // Apply states
  9357. this.applyStates();
  9358. this._drawCalls.addCount(1, false);
  9359. if (instancesCount) {
  9360. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9361. return;
  9362. }
  9363. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9364. };
  9365. // Shaders
  9366. Engine.prototype._releaseEffect = function (effect) {
  9367. if (this._compiledEffects[effect._key]) {
  9368. delete this._compiledEffects[effect._key];
  9369. if (effect.getProgram()) {
  9370. this._gl.deleteProgram(effect.getProgram());
  9371. }
  9372. }
  9373. };
  9374. /**
  9375. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9376. * @param samplers An array of string used to represent textures
  9377. */
  9378. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9379. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9380. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9381. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9382. if (this._compiledEffects[name]) {
  9383. var compiledEffect = this._compiledEffects[name];
  9384. if (onCompiled && compiledEffect.isReady()) {
  9385. onCompiled(compiledEffect);
  9386. }
  9387. return compiledEffect;
  9388. }
  9389. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9390. effect._key = name;
  9391. this._compiledEffects[name] = effect;
  9392. return effect;
  9393. };
  9394. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9395. if (uniformsNames === void 0) { uniformsNames = []; }
  9396. if (samplers === void 0) { samplers = []; }
  9397. if (defines === void 0) { defines = ""; }
  9398. return this.createEffect({
  9399. vertex: "particles",
  9400. fragmentElement: fragmentName
  9401. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9402. };
  9403. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9404. context = context || this._gl;
  9405. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9406. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9407. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9408. var shaderProgram = context.createProgram();
  9409. context.attachShader(shaderProgram, vertexShader);
  9410. context.attachShader(shaderProgram, fragmentShader);
  9411. context.linkProgram(shaderProgram);
  9412. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9413. if (!linked) {
  9414. context.validateProgram(shaderProgram);
  9415. var error = context.getProgramInfoLog(shaderProgram);
  9416. if (error) {
  9417. throw new Error(error);
  9418. }
  9419. }
  9420. context.deleteShader(vertexShader);
  9421. context.deleteShader(fragmentShader);
  9422. return shaderProgram;
  9423. };
  9424. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9425. var results = [];
  9426. for (var index = 0; index < uniformsNames.length; index++) {
  9427. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9428. }
  9429. return results;
  9430. };
  9431. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9432. var results = [];
  9433. for (var index = 0; index < attributesNames.length; index++) {
  9434. try {
  9435. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9436. }
  9437. catch (e) {
  9438. results.push(-1);
  9439. }
  9440. }
  9441. return results;
  9442. };
  9443. Engine.prototype.enableEffect = function (effect) {
  9444. // Use program
  9445. this.setProgram(effect.getProgram());
  9446. this._currentEffect = effect;
  9447. if (effect.onBind) {
  9448. effect.onBind(effect);
  9449. }
  9450. effect.onBindObservable.notifyObservers(effect);
  9451. };
  9452. Engine.prototype.setIntArray = function (uniform, array) {
  9453. if (!uniform)
  9454. return;
  9455. this._gl.uniform1iv(uniform, array);
  9456. };
  9457. Engine.prototype.setIntArray2 = function (uniform, array) {
  9458. if (!uniform || array.length % 2 !== 0)
  9459. return;
  9460. this._gl.uniform2iv(uniform, array);
  9461. };
  9462. Engine.prototype.setIntArray3 = function (uniform, array) {
  9463. if (!uniform || array.length % 3 !== 0)
  9464. return;
  9465. this._gl.uniform3iv(uniform, array);
  9466. };
  9467. Engine.prototype.setIntArray4 = function (uniform, array) {
  9468. if (!uniform || array.length % 4 !== 0)
  9469. return;
  9470. this._gl.uniform4iv(uniform, array);
  9471. };
  9472. Engine.prototype.setFloatArray = function (uniform, array) {
  9473. if (!uniform)
  9474. return;
  9475. this._gl.uniform1fv(uniform, array);
  9476. };
  9477. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9478. if (!uniform || array.length % 2 !== 0)
  9479. return;
  9480. this._gl.uniform2fv(uniform, array);
  9481. };
  9482. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9483. if (!uniform || array.length % 3 !== 0)
  9484. return;
  9485. this._gl.uniform3fv(uniform, array);
  9486. };
  9487. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9488. if (!uniform || array.length % 4 !== 0)
  9489. return;
  9490. this._gl.uniform4fv(uniform, array);
  9491. };
  9492. Engine.prototype.setArray = function (uniform, array) {
  9493. if (!uniform)
  9494. return;
  9495. this._gl.uniform1fv(uniform, array);
  9496. };
  9497. Engine.prototype.setArray2 = function (uniform, array) {
  9498. if (!uniform || array.length % 2 !== 0)
  9499. return;
  9500. this._gl.uniform2fv(uniform, array);
  9501. };
  9502. Engine.prototype.setArray3 = function (uniform, array) {
  9503. if (!uniform || array.length % 3 !== 0)
  9504. return;
  9505. this._gl.uniform3fv(uniform, array);
  9506. };
  9507. Engine.prototype.setArray4 = function (uniform, array) {
  9508. if (!uniform || array.length % 4 !== 0)
  9509. return;
  9510. this._gl.uniform4fv(uniform, array);
  9511. };
  9512. Engine.prototype.setMatrices = function (uniform, matrices) {
  9513. if (!uniform)
  9514. return;
  9515. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9516. };
  9517. Engine.prototype.setMatrix = function (uniform, matrix) {
  9518. if (!uniform)
  9519. return;
  9520. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9521. };
  9522. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9523. if (!uniform)
  9524. return;
  9525. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9526. };
  9527. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9528. if (!uniform)
  9529. return;
  9530. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9531. };
  9532. Engine.prototype.setFloat = function (uniform, value) {
  9533. if (!uniform)
  9534. return;
  9535. this._gl.uniform1f(uniform, value);
  9536. };
  9537. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9538. if (!uniform)
  9539. return;
  9540. this._gl.uniform2f(uniform, x, y);
  9541. };
  9542. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9543. if (!uniform)
  9544. return;
  9545. this._gl.uniform3f(uniform, x, y, z);
  9546. };
  9547. Engine.prototype.setBool = function (uniform, bool) {
  9548. if (!uniform)
  9549. return;
  9550. this._gl.uniform1i(uniform, bool);
  9551. };
  9552. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9553. if (!uniform)
  9554. return;
  9555. this._gl.uniform4f(uniform, x, y, z, w);
  9556. };
  9557. Engine.prototype.setColor3 = function (uniform, color3) {
  9558. if (!uniform)
  9559. return;
  9560. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9561. };
  9562. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9563. if (!uniform)
  9564. return;
  9565. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9566. };
  9567. // States
  9568. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9569. if (zOffset === void 0) { zOffset = 0; }
  9570. if (reverseSide === void 0) { reverseSide = false; }
  9571. // Culling
  9572. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9573. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9574. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9575. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9576. if (culling) {
  9577. this._depthCullingState.cullFace = cullFace;
  9578. this._depthCullingState.cull = true;
  9579. }
  9580. else {
  9581. this._depthCullingState.cull = false;
  9582. }
  9583. }
  9584. // Z offset
  9585. this.setZOffset(zOffset);
  9586. };
  9587. Engine.prototype.setZOffset = function (value) {
  9588. this._depthCullingState.zOffset = value;
  9589. };
  9590. Engine.prototype.getZOffset = function () {
  9591. return this._depthCullingState.zOffset;
  9592. };
  9593. Engine.prototype.setDepthBuffer = function (enable) {
  9594. this._depthCullingState.depthTest = enable;
  9595. };
  9596. Engine.prototype.getDepthWrite = function () {
  9597. return this._depthCullingState.depthMask;
  9598. };
  9599. Engine.prototype.setDepthWrite = function (enable) {
  9600. this._depthCullingState.depthMask = enable;
  9601. };
  9602. Engine.prototype.setColorWrite = function (enable) {
  9603. this._gl.colorMask(enable, enable, enable, enable);
  9604. this._colorWrite = enable;
  9605. };
  9606. Engine.prototype.getColorWrite = function () {
  9607. return this._colorWrite;
  9608. };
  9609. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9610. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9611. };
  9612. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9613. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9614. if (this._alphaMode === mode) {
  9615. return;
  9616. }
  9617. switch (mode) {
  9618. case Engine.ALPHA_DISABLE:
  9619. this._alphaState.alphaBlend = false;
  9620. break;
  9621. case Engine.ALPHA_PREMULTIPLIED:
  9622. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9623. this._alphaState.alphaBlend = true;
  9624. break;
  9625. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9626. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9627. this._alphaState.alphaBlend = true;
  9628. break;
  9629. case Engine.ALPHA_COMBINE:
  9630. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9631. this._alphaState.alphaBlend = true;
  9632. break;
  9633. case Engine.ALPHA_ONEONE:
  9634. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9635. this._alphaState.alphaBlend = true;
  9636. break;
  9637. case Engine.ALPHA_ADD:
  9638. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9639. this._alphaState.alphaBlend = true;
  9640. break;
  9641. case Engine.ALPHA_SUBTRACT:
  9642. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9643. this._alphaState.alphaBlend = true;
  9644. break;
  9645. case Engine.ALPHA_MULTIPLY:
  9646. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9647. this._alphaState.alphaBlend = true;
  9648. break;
  9649. case Engine.ALPHA_MAXIMIZED:
  9650. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9651. this._alphaState.alphaBlend = true;
  9652. break;
  9653. case Engine.ALPHA_INTERPOLATE:
  9654. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9655. this._alphaState.alphaBlend = true;
  9656. break;
  9657. case Engine.ALPHA_SCREENMODE:
  9658. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9659. this._alphaState.alphaBlend = true;
  9660. break;
  9661. }
  9662. if (!noDepthWriteChange) {
  9663. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9664. }
  9665. this._alphaMode = mode;
  9666. };
  9667. Engine.prototype.getAlphaMode = function () {
  9668. return this._alphaMode;
  9669. };
  9670. Engine.prototype.setAlphaTesting = function (enable) {
  9671. this._alphaTest = enable;
  9672. };
  9673. Engine.prototype.getAlphaTesting = function () {
  9674. return !!this._alphaTest;
  9675. };
  9676. // Textures
  9677. Engine.prototype.wipeCaches = function (bruteForce) {
  9678. if (this.preventCacheWipeBetweenFrames) {
  9679. return;
  9680. }
  9681. this.resetTextureCache();
  9682. this._currentEffect = null;
  9683. // 6/8/2017: deltakosh: Should not be required anymore.
  9684. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9685. if (bruteForce) {
  9686. this._currentProgram = null;
  9687. this._stencilState.reset();
  9688. this._depthCullingState.reset();
  9689. this.setDepthFunctionToLessOrEqual();
  9690. this._alphaState.reset();
  9691. }
  9692. this._cachedVertexBuffers = null;
  9693. this._cachedIndexBuffer = null;
  9694. this._cachedEffectForVertexBuffers = null;
  9695. this._unbindVertexArrayObject();
  9696. this.bindIndexBuffer(null);
  9697. this.bindArrayBuffer(null);
  9698. };
  9699. /**
  9700. * Set the compressed texture format to use, based on the formats you have, and the formats
  9701. * supported by the hardware / browser.
  9702. *
  9703. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9704. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9705. * to API arguments needed to compressed textures. This puts the burden on the container
  9706. * generator to house the arcane code for determining these for current & future formats.
  9707. *
  9708. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9709. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9710. *
  9711. * Note: The result of this call is not taken into account when a texture is base64.
  9712. *
  9713. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9714. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9715. *
  9716. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9717. * @returns The extension selected.
  9718. */
  9719. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9720. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9721. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9722. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9723. return this._textureFormatInUse = this._texturesSupported[i];
  9724. }
  9725. }
  9726. }
  9727. // actively set format to nothing, to allow this to be called more than once
  9728. // and possibly fail the 2nd time
  9729. return this._textureFormatInUse = null;
  9730. };
  9731. Engine.prototype._createTexture = function () {
  9732. return this._gl.createTexture();
  9733. };
  9734. /**
  9735. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9736. * @param {string} urlArg- This contains one of the following:
  9737. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9738. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9739. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9740. *
  9741. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9742. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9743. * @param {Scene} scene- Needed for loading to the correct scene.
  9744. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9745. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9746. * @param {callback} onError- Optional callback to be called upon failure.
  9747. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9748. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9749. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9750. *
  9751. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9752. */
  9753. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9754. var _this = this;
  9755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9756. if (onLoad === void 0) { onLoad = null; }
  9757. if (onError === void 0) { onError = null; }
  9758. if (buffer === void 0) { buffer = null; }
  9759. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9760. var fromData = url.substr(0, 5) === "data:";
  9761. var fromBlob = url.substr(0, 5) === "blob:";
  9762. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9763. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9764. // establish the file extension, if possible
  9765. var lastDot = url.lastIndexOf('.');
  9766. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9767. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9768. var isTGA = (extension === ".tga");
  9769. // determine if a ktx file should be substituted
  9770. var isKTX = false;
  9771. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9772. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9773. isKTX = true;
  9774. }
  9775. if (scene) {
  9776. scene._addPendingData(texture);
  9777. }
  9778. texture.url = url;
  9779. texture.generateMipMaps = !noMipmap;
  9780. texture.samplingMode = samplingMode;
  9781. texture.invertY = invertY;
  9782. if (!this._doNotHandleContextLost) {
  9783. // Keep a link to the buffer only if we plan to handle context lost
  9784. texture._buffer = buffer;
  9785. }
  9786. if (onLoad) {
  9787. texture.onLoadedObservable.add(onLoad);
  9788. }
  9789. if (!fallBack)
  9790. this._internalTexturesCache.push(texture);
  9791. var onerror = function () {
  9792. if (scene) {
  9793. scene._removePendingData(texture);
  9794. }
  9795. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9796. if (isKTX) {
  9797. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9798. }
  9799. else if (onError) {
  9800. onError();
  9801. }
  9802. };
  9803. var callback;
  9804. // processing for non-image formats
  9805. if (isKTX || isTGA || isDDS) {
  9806. if (isKTX) {
  9807. callback = function (data) {
  9808. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9809. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9810. ktx.uploadLevels(_this._gl, !noMipmap);
  9811. return false;
  9812. }, samplingMode);
  9813. };
  9814. }
  9815. else if (isTGA) {
  9816. callback = function (arrayBuffer) {
  9817. var data = new Uint8Array(arrayBuffer);
  9818. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9819. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9820. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9821. return false;
  9822. }, samplingMode);
  9823. };
  9824. }
  9825. else if (isDDS) {
  9826. callback = function (data) {
  9827. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9828. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9829. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9830. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9831. return false;
  9832. }, samplingMode);
  9833. };
  9834. }
  9835. if (!buffer) {
  9836. BABYLON.Tools.LoadFile(url, function (data) {
  9837. callback(data);
  9838. }, null, scene ? scene.database : null, true, onerror);
  9839. }
  9840. else {
  9841. callback(buffer);
  9842. }
  9843. // image format processing
  9844. }
  9845. else {
  9846. var onload = function (img) {
  9847. if (fromBlob && !_this._doNotHandleContextLost) {
  9848. // We need to store the image if we need to rebuild the texture
  9849. // in case of a webgl context lost
  9850. texture._buffer = img;
  9851. }
  9852. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9853. var gl = _this._gl;
  9854. var isPot = (img.width === potWidth && img.height === potHeight);
  9855. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9856. if (isPot) {
  9857. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9858. return false;
  9859. }
  9860. // Using shaders to rescale because canvas.drawImage is lossy
  9861. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9862. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9863. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9864. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9865. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9868. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9869. _this._releaseTexture(source);
  9870. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9871. continuationCallback();
  9872. });
  9873. return true;
  9874. }, samplingMode);
  9875. };
  9876. if (!fromData || isBase64)
  9877. if (buffer instanceof HTMLImageElement) {
  9878. onload(buffer);
  9879. }
  9880. else {
  9881. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9882. }
  9883. else if (buffer instanceof Array || typeof buffer === "string")
  9884. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9885. else
  9886. onload(buffer);
  9887. }
  9888. return texture;
  9889. };
  9890. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9891. var _this = this;
  9892. var rtt = this.createRenderTargetTexture({
  9893. width: destination.width,
  9894. height: destination.height,
  9895. }, {
  9896. generateMipMaps: false,
  9897. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9898. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9899. generateDepthBuffer: false,
  9900. generateStencilBuffer: false
  9901. });
  9902. if (!this._rescalePostProcess) {
  9903. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9904. }
  9905. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9906. _this._rescalePostProcess.onApply = function (effect) {
  9907. effect._bindTexture("textureSampler", source);
  9908. };
  9909. var hostingScene = scene;
  9910. if (!hostingScene) {
  9911. hostingScene = _this.scenes[_this.scenes.length - 1];
  9912. }
  9913. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9914. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9915. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9916. _this.unBindFramebuffer(rtt);
  9917. _this._releaseTexture(rtt);
  9918. if (onComplete) {
  9919. onComplete();
  9920. }
  9921. });
  9922. };
  9923. Engine.prototype._getInternalFormat = function (format) {
  9924. var internalFormat = this._gl.RGBA;
  9925. switch (format) {
  9926. case Engine.TEXTUREFORMAT_ALPHA:
  9927. internalFormat = this._gl.ALPHA;
  9928. break;
  9929. case Engine.TEXTUREFORMAT_LUMINANCE:
  9930. internalFormat = this._gl.LUMINANCE;
  9931. break;
  9932. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9933. internalFormat = this._gl.LUMINANCE_ALPHA;
  9934. break;
  9935. case Engine.TEXTUREFORMAT_RGB:
  9936. internalFormat = this._gl.RGB;
  9937. break;
  9938. case Engine.TEXTUREFORMAT_RGBA:
  9939. internalFormat = this._gl.RGBA;
  9940. break;
  9941. }
  9942. return internalFormat;
  9943. };
  9944. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9945. if (compression === void 0) { compression = null; }
  9946. var internalFormat = this._getInternalFormat(format);
  9947. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9948. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9949. if (!this._doNotHandleContextLost) {
  9950. texture._bufferView = data;
  9951. texture.format = format;
  9952. texture.invertY = invertY;
  9953. texture._compression = compression;
  9954. }
  9955. if (texture.width % 4 !== 0) {
  9956. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9957. }
  9958. if (compression) {
  9959. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9960. }
  9961. else {
  9962. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9963. }
  9964. if (texture.generateMipMaps) {
  9965. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9966. }
  9967. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9968. this.resetTextureCache();
  9969. texture.isReady = true;
  9970. };
  9971. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9972. if (compression === void 0) { compression = null; }
  9973. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9974. texture.baseWidth = width;
  9975. texture.baseHeight = height;
  9976. texture.width = width;
  9977. texture.height = height;
  9978. texture.format = format;
  9979. texture.generateMipMaps = generateMipMaps;
  9980. texture.samplingMode = samplingMode;
  9981. texture.invertY = invertY;
  9982. texture._compression = compression;
  9983. if (!this._doNotHandleContextLost) {
  9984. texture._bufferView = data;
  9985. }
  9986. this.updateRawTexture(texture, data, format, invertY, compression);
  9987. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9988. // Filters
  9989. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9990. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9991. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9992. if (generateMipMaps) {
  9993. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9994. }
  9995. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9996. this._internalTexturesCache.push(texture);
  9997. return texture;
  9998. };
  9999. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10000. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10001. texture.baseWidth = width;
  10002. texture.baseHeight = height;
  10003. if (generateMipMaps) {
  10004. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10005. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10006. }
  10007. this.resetTextureCache();
  10008. texture.width = width;
  10009. texture.height = height;
  10010. texture.isReady = false;
  10011. texture.generateMipMaps = generateMipMaps;
  10012. texture.samplingMode = samplingMode;
  10013. this.updateTextureSamplingMode(samplingMode, texture);
  10014. this._internalTexturesCache.push(texture);
  10015. return texture;
  10016. };
  10017. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10018. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10019. if (texture.isCube) {
  10020. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10021. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10022. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10023. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10024. }
  10025. else {
  10026. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10027. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10029. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10030. }
  10031. texture.samplingMode = samplingMode;
  10032. };
  10033. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10034. if (premulAlpha === void 0) { premulAlpha = false; }
  10035. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10036. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10037. if (premulAlpha) {
  10038. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10039. }
  10040. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10041. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10042. if (texture.generateMipMaps) {
  10043. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10044. }
  10045. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10046. if (premulAlpha) {
  10047. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10048. }
  10049. this.resetTextureCache();
  10050. texture.isReady = true;
  10051. };
  10052. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10053. if (texture._isDisabled) {
  10054. return;
  10055. }
  10056. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10057. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10058. try {
  10059. // Testing video texture support
  10060. if (this._videoTextureSupported === undefined) {
  10061. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10062. if (this._gl.getError() !== 0) {
  10063. this._videoTextureSupported = false;
  10064. }
  10065. else {
  10066. this._videoTextureSupported = true;
  10067. }
  10068. }
  10069. // Copy video through the current working canvas if video texture is not supported
  10070. if (!this._videoTextureSupported) {
  10071. if (!texture._workingCanvas) {
  10072. texture._workingCanvas = document.createElement("canvas");
  10073. texture._workingContext = texture._workingCanvas.getContext("2d");
  10074. texture._workingCanvas.width = texture.width;
  10075. texture._workingCanvas.height = texture.height;
  10076. }
  10077. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10078. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10079. }
  10080. else {
  10081. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10082. }
  10083. if (texture.generateMipMaps) {
  10084. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10085. }
  10086. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10087. this.resetTextureCache();
  10088. texture.isReady = true;
  10089. }
  10090. catch (ex) {
  10091. // Something unexpected
  10092. // Let's disable the texture
  10093. texture._isDisabled = true;
  10094. }
  10095. };
  10096. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10097. var fullOptions = new RenderTargetCreationOptions();
  10098. if (options !== undefined && typeof options === "object") {
  10099. fullOptions.generateMipMaps = options.generateMipMaps;
  10100. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10101. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10102. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10103. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10104. }
  10105. else {
  10106. fullOptions.generateMipMaps = options;
  10107. fullOptions.generateDepthBuffer = true;
  10108. fullOptions.generateStencilBuffer = false;
  10109. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10110. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10111. }
  10112. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10113. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10114. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10115. }
  10116. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10117. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10118. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10119. }
  10120. var gl = this._gl;
  10121. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10122. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10123. var width = size.width || size;
  10124. var height = size.height || size;
  10125. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10126. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10127. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10128. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10129. }
  10130. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10131. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10132. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10134. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10135. // Create the framebuffer
  10136. var framebuffer = gl.createFramebuffer();
  10137. this.bindUnboundFramebuffer(framebuffer);
  10138. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10139. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10140. if (fullOptions.generateMipMaps) {
  10141. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10142. }
  10143. // Unbind
  10144. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10145. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10146. this.bindUnboundFramebuffer(null);
  10147. texture._framebuffer = framebuffer;
  10148. texture.baseWidth = width;
  10149. texture.baseHeight = height;
  10150. texture.width = width;
  10151. texture.height = height;
  10152. texture.isReady = true;
  10153. texture.samples = 1;
  10154. texture.generateMipMaps = fullOptions.generateMipMaps;
  10155. texture.samplingMode = fullOptions.samplingMode;
  10156. texture.type = fullOptions.type;
  10157. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10158. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10159. this.resetTextureCache();
  10160. this._internalTexturesCache.push(texture);
  10161. return texture;
  10162. };
  10163. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10164. var generateMipMaps = false;
  10165. var generateDepthBuffer = true;
  10166. var generateStencilBuffer = false;
  10167. var generateDepthTexture = false;
  10168. var textureCount = 1;
  10169. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10170. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10171. var types = [], samplingModes = [];
  10172. if (options !== undefined) {
  10173. generateMipMaps = options.generateMipMaps;
  10174. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10175. generateStencilBuffer = options.generateStencilBuffer;
  10176. generateDepthTexture = options.generateDepthTexture;
  10177. textureCount = options.textureCount || 1;
  10178. if (options.types) {
  10179. types = options.types;
  10180. }
  10181. if (options.samplingModes) {
  10182. samplingModes = options.samplingModes;
  10183. }
  10184. }
  10185. var gl = this._gl;
  10186. // Create the framebuffer
  10187. var framebuffer = gl.createFramebuffer();
  10188. this.bindUnboundFramebuffer(framebuffer);
  10189. var width = size.width || size;
  10190. var height = size.height || size;
  10191. var textures = [];
  10192. var attachments = [];
  10193. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10194. for (var i = 0; i < textureCount; i++) {
  10195. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10196. var type = types[i] || defaultType;
  10197. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10198. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10199. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10200. }
  10201. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10202. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10203. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10204. }
  10205. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10206. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10207. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10208. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10209. }
  10210. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10211. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10212. textures.push(texture);
  10213. attachments.push(attachment);
  10214. gl.activeTexture(gl["TEXTURE" + i]);
  10215. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10220. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10221. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10222. if (generateMipMaps) {
  10223. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10224. }
  10225. // Unbind
  10226. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10227. texture._framebuffer = framebuffer;
  10228. texture._depthStencilBuffer = depthStencilBuffer;
  10229. texture.baseWidth = width;
  10230. texture.baseHeight = height;
  10231. texture.width = width;
  10232. texture.height = height;
  10233. texture.isReady = true;
  10234. texture.samples = 1;
  10235. texture.generateMipMaps = generateMipMaps;
  10236. texture.samplingMode = samplingMode;
  10237. texture.type = type;
  10238. texture._generateDepthBuffer = generateDepthBuffer;
  10239. texture._generateStencilBuffer = generateStencilBuffer;
  10240. this._internalTexturesCache.push(texture);
  10241. }
  10242. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10243. // Depth texture
  10244. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10245. gl.activeTexture(gl.TEXTURE0);
  10246. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10249. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10250. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10251. 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);
  10252. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10253. depthTexture._framebuffer = framebuffer;
  10254. depthTexture.baseWidth = width;
  10255. depthTexture.baseHeight = height;
  10256. depthTexture.width = width;
  10257. depthTexture.height = height;
  10258. depthTexture.isReady = true;
  10259. depthTexture.samples = 1;
  10260. depthTexture.generateMipMaps = generateMipMaps;
  10261. depthTexture.samplingMode = gl.NEAREST;
  10262. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10263. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10264. textures.push(depthTexture);
  10265. this._internalTexturesCache.push(depthTexture);
  10266. }
  10267. gl.drawBuffers(attachments);
  10268. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10269. this.bindUnboundFramebuffer(null);
  10270. this.resetTextureCache();
  10271. return textures;
  10272. };
  10273. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10274. if (samples === void 0) { samples = 1; }
  10275. var depthStencilBuffer = null;
  10276. var gl = this._gl;
  10277. // Create the depth/stencil buffer
  10278. if (generateStencilBuffer) {
  10279. depthStencilBuffer = gl.createRenderbuffer();
  10280. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10281. if (samples > 1) {
  10282. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10283. }
  10284. else {
  10285. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10286. }
  10287. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10288. }
  10289. else if (generateDepthBuffer) {
  10290. depthStencilBuffer = gl.createRenderbuffer();
  10291. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10292. if (samples > 1) {
  10293. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10294. }
  10295. else {
  10296. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10297. }
  10298. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10299. }
  10300. return depthStencilBuffer;
  10301. };
  10302. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10303. if (this.webGLVersion < 2) {
  10304. return 1;
  10305. }
  10306. if (texture.samples === samples) {
  10307. return samples;
  10308. }
  10309. var gl = this._gl;
  10310. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10311. // Dispose previous render buffers
  10312. if (texture._depthStencilBuffer) {
  10313. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10314. }
  10315. if (texture._MSAAFramebuffer) {
  10316. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10317. }
  10318. if (texture._MSAARenderBuffer) {
  10319. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10320. }
  10321. if (samples > 1) {
  10322. texture._MSAAFramebuffer = gl.createFramebuffer();
  10323. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10324. var colorRenderbuffer = gl.createRenderbuffer();
  10325. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10326. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10327. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10328. texture._MSAARenderBuffer = colorRenderbuffer;
  10329. }
  10330. else {
  10331. this.bindUnboundFramebuffer(texture._framebuffer);
  10332. }
  10333. texture.samples = samples;
  10334. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10335. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10336. this.bindUnboundFramebuffer(null);
  10337. return samples;
  10338. };
  10339. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10340. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10341. };
  10342. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10343. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10344. };
  10345. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10346. var gl = this._gl;
  10347. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10348. var generateMipMaps = true;
  10349. var generateDepthBuffer = true;
  10350. var generateStencilBuffer = false;
  10351. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10352. if (options !== undefined) {
  10353. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10354. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10355. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10356. if (options.samplingMode !== undefined) {
  10357. samplingMode = options.samplingMode;
  10358. }
  10359. }
  10360. texture.isCube = true;
  10361. texture.generateMipMaps = generateMipMaps;
  10362. texture.samples = 1;
  10363. texture.samplingMode = samplingMode;
  10364. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10365. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10366. for (var face = 0; face < 6; face++) {
  10367. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10368. }
  10369. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10370. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10371. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10373. // Create the framebuffer
  10374. var framebuffer = gl.createFramebuffer();
  10375. this.bindUnboundFramebuffer(framebuffer);
  10376. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10377. // Mipmaps
  10378. if (texture.generateMipMaps) {
  10379. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10380. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10381. }
  10382. // Unbind
  10383. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10384. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10385. this.bindUnboundFramebuffer(null);
  10386. texture._framebuffer = framebuffer;
  10387. texture.width = size;
  10388. texture.height = size;
  10389. texture.isReady = true;
  10390. this.resetTextureCache();
  10391. this._internalTexturesCache.push(texture);
  10392. return texture;
  10393. };
  10394. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10395. var _this = this;
  10396. if (onError === void 0) { onError = null; }
  10397. if (forcedExtension === void 0) { forcedExtension = null; }
  10398. var callback = function (loadData) {
  10399. if (!loadData) {
  10400. if (onLoad) {
  10401. onLoad(null);
  10402. }
  10403. return;
  10404. }
  10405. var texture = loadData.texture;
  10406. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10407. texture._lodGenerationScale = scale;
  10408. texture._lodGenerationOffset = offset;
  10409. if (_this._caps.textureLOD) {
  10410. // Do not add extra process if texture lod is supported.
  10411. if (onLoad) {
  10412. onLoad(texture);
  10413. }
  10414. return;
  10415. }
  10416. var mipSlices = 3;
  10417. var gl = _this._gl;
  10418. var width = loadData.width;
  10419. if (!width) {
  10420. return;
  10421. }
  10422. var textures = [];
  10423. for (var i = 0; i < mipSlices; i++) {
  10424. //compute LOD from even spacing in smoothness (matching shader calculation)
  10425. var smoothness = i / (mipSlices - 1);
  10426. var roughness = 1 - smoothness;
  10427. var minLODIndex = offset; // roughness = 0
  10428. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10429. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10430. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10431. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10432. glTextureFromLod.isCube = true;
  10433. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10434. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10438. if (loadData.isDDS) {
  10439. var info = loadData.info;
  10440. var data = loadData.data;
  10441. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10442. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10443. }
  10444. else {
  10445. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10446. }
  10447. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10448. // Wrap in a base texture for easy binding.
  10449. var lodTexture = new BABYLON.BaseTexture(scene);
  10450. lodTexture.isCube = true;
  10451. lodTexture._texture = glTextureFromLod;
  10452. glTextureFromLod.isReady = true;
  10453. textures.push(lodTexture);
  10454. }
  10455. texture._lodTextureHigh = textures[2];
  10456. texture._lodTextureMid = textures[1];
  10457. texture._lodTextureLow = textures[0];
  10458. if (onLoad) {
  10459. onLoad(texture);
  10460. }
  10461. };
  10462. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10463. };
  10464. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10465. var _this = this;
  10466. if (onLoad === void 0) { onLoad = null; }
  10467. if (onError === void 0) { onError = null; }
  10468. if (forcedExtension === void 0) { forcedExtension = null; }
  10469. var gl = this._gl;
  10470. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10471. texture.isCube = true;
  10472. texture.url = rootUrl;
  10473. texture.generateMipMaps = !noMipmap;
  10474. if (!this._doNotHandleContextLost) {
  10475. texture._extension = forcedExtension;
  10476. texture._files = files;
  10477. }
  10478. var isKTX = false;
  10479. var isDDS = false;
  10480. var lastDot = rootUrl.lastIndexOf('.');
  10481. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10482. if (this._textureFormatInUse) {
  10483. extension = this._textureFormatInUse;
  10484. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10485. isKTX = true;
  10486. }
  10487. else {
  10488. isDDS = (extension === ".dds");
  10489. }
  10490. if (isKTX) {
  10491. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10492. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10493. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10494. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10495. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10496. ktx.uploadLevels(_this._gl, !noMipmap);
  10497. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10498. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10499. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10501. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10502. _this.resetTextureCache();
  10503. texture.width = ktx.pixelWidth;
  10504. texture.height = ktx.pixelHeight;
  10505. texture.isReady = true;
  10506. }, null, null, true, onError);
  10507. }
  10508. else if (isDDS) {
  10509. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10510. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10511. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10512. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10513. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10514. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10515. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10516. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10517. }
  10518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10519. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10521. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10522. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10523. _this.resetTextureCache();
  10524. texture.width = info.width;
  10525. texture.height = info.height;
  10526. texture.isReady = true;
  10527. texture.type = info.textureType;
  10528. if (onLoad) {
  10529. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10530. }
  10531. }, null, null, true, onError);
  10532. }
  10533. else {
  10534. cascadeLoad(rootUrl, scene, function (imgs) {
  10535. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10536. var height = width;
  10537. _this._prepareWorkingCanvas();
  10538. _this._workingCanvas.width = width;
  10539. _this._workingCanvas.height = height;
  10540. var faces = [
  10541. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10542. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10543. ];
  10544. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10545. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10546. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10547. for (var index = 0; index < faces.length; index++) {
  10548. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10549. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10550. }
  10551. if (!noMipmap) {
  10552. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10553. }
  10554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10558. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10559. _this.resetTextureCache();
  10560. texture.width = width;
  10561. texture.height = height;
  10562. texture.isReady = true;
  10563. texture.format = format;
  10564. texture.onLoadedObservable.notifyObservers(texture);
  10565. texture.onLoadedObservable.clear();
  10566. if (onLoad) {
  10567. onLoad();
  10568. }
  10569. }, files, onError);
  10570. }
  10571. this._internalTexturesCache.push(texture);
  10572. return texture;
  10573. };
  10574. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10575. if (compression === void 0) { compression = null; }
  10576. if (level === void 0) { level = 0; }
  10577. texture._bufferViewArray = data;
  10578. texture.format = format;
  10579. texture.type = type;
  10580. texture.invertY = invertY;
  10581. texture._compression = compression;
  10582. var gl = this._gl;
  10583. var textureType = this._getWebGLTextureType(type);
  10584. var internalFormat = this._getInternalFormat(format);
  10585. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10586. var needConversion = false;
  10587. if (internalFormat === gl.RGB) {
  10588. internalFormat = gl.RGBA;
  10589. needConversion = true;
  10590. }
  10591. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10592. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10593. if (texture.width % 4 !== 0) {
  10594. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10595. }
  10596. // Data are known to be in +X +Y +Z -X -Y -Z
  10597. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10598. var faceData = data[faceIndex];
  10599. if (compression) {
  10600. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10601. }
  10602. else {
  10603. if (needConversion) {
  10604. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10605. }
  10606. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10607. }
  10608. }
  10609. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10610. if (isPot && texture.generateMipMaps && level === 0) {
  10611. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10612. }
  10613. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10614. this.resetTextureCache();
  10615. texture.isReady = true;
  10616. };
  10617. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10618. if (compression === void 0) { compression = null; }
  10619. var gl = this._gl;
  10620. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10621. texture.isCube = true;
  10622. texture.generateMipMaps = generateMipMaps;
  10623. texture.format = format;
  10624. texture.type = type;
  10625. if (!this._doNotHandleContextLost) {
  10626. texture._bufferViewArray = data;
  10627. }
  10628. var textureType = this._getWebGLTextureType(type);
  10629. var internalFormat = this._getInternalFormat(format);
  10630. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10631. var needConversion = false;
  10632. if (internalFormat === gl.RGB) {
  10633. internalFormat = gl.RGBA;
  10634. needConversion = true;
  10635. }
  10636. var width = size;
  10637. var height = width;
  10638. texture.width = width;
  10639. texture.height = height;
  10640. // Double check on POT to generate Mips.
  10641. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10642. if (!isPot) {
  10643. generateMipMaps = false;
  10644. }
  10645. // Upload data if needed. The texture won't be ready until then.
  10646. if (data) {
  10647. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10648. }
  10649. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10650. // Filters
  10651. if (data && generateMipMaps) {
  10652. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10653. }
  10654. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10656. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10657. }
  10658. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10659. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10660. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10661. }
  10662. else {
  10663. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10666. }
  10667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10668. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10669. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10670. return texture;
  10671. };
  10672. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10673. var _this = this;
  10674. if (onLoad === void 0) { onLoad = null; }
  10675. if (onError === void 0) { onError = null; }
  10676. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10677. if (invertY === void 0) { invertY = false; }
  10678. var gl = this._gl;
  10679. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10680. scene._addPendingData(texture);
  10681. texture.url = url;
  10682. this._internalTexturesCache.push(texture);
  10683. var onerror = function () {
  10684. scene._removePendingData(texture);
  10685. if (onError) {
  10686. onError();
  10687. }
  10688. };
  10689. var internalCallback = function (data) {
  10690. var width = texture.width;
  10691. var height = texture.height;
  10692. var faceDataArrays = callback(data);
  10693. if (mipmmapGenerator) {
  10694. var textureType = _this._getWebGLTextureType(type);
  10695. var internalFormat = _this._getInternalFormat(format);
  10696. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10697. var needConversion = false;
  10698. if (internalFormat === gl.RGB) {
  10699. internalFormat = gl.RGBA;
  10700. needConversion = true;
  10701. }
  10702. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10703. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10704. var mipData = mipmmapGenerator(faceDataArrays);
  10705. for (var level = 0; level < mipData.length; level++) {
  10706. var mipSize = width >> level;
  10707. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10708. var mipFaceData = mipData[level][faceIndex];
  10709. if (needConversion) {
  10710. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10711. }
  10712. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10713. }
  10714. }
  10715. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10716. }
  10717. else {
  10718. texture.generateMipMaps = !noMipmap;
  10719. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10720. }
  10721. texture.isReady = true;
  10722. _this.resetTextureCache();
  10723. scene._removePendingData(texture);
  10724. if (onLoad) {
  10725. onLoad();
  10726. }
  10727. };
  10728. BABYLON.Tools.LoadFile(url, function (data) {
  10729. internalCallback(data);
  10730. }, onerror, scene.database, true);
  10731. return texture;
  10732. };
  10733. ;
  10734. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10735. var gl = this._gl;
  10736. if (!gl) {
  10737. return;
  10738. }
  10739. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10740. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10741. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10742. if (!noMipmap && !isCompressed) {
  10743. gl.generateMipmap(gl.TEXTURE_2D);
  10744. }
  10745. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10746. this.resetTextureCache();
  10747. if (scene) {
  10748. scene._removePendingData(texture);
  10749. }
  10750. texture.onLoadedObservable.notifyObservers(texture);
  10751. texture.onLoadedObservable.clear();
  10752. };
  10753. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10754. var _this = this;
  10755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10756. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10757. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10758. var gl = this._gl;
  10759. if (!gl) {
  10760. return;
  10761. }
  10762. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10763. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10764. texture.baseWidth = width;
  10765. texture.baseHeight = height;
  10766. texture.width = potWidth;
  10767. texture.height = potHeight;
  10768. texture.isReady = true;
  10769. if (processFunction(potWidth, potHeight, function () {
  10770. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10771. })) {
  10772. // Returning as texture needs extra async steps
  10773. return;
  10774. }
  10775. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10776. };
  10777. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10778. // Create new RGBA data container.
  10779. var rgbaData;
  10780. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10781. rgbaData = new Float32Array(width * height * 4);
  10782. }
  10783. else {
  10784. rgbaData = new Uint32Array(width * height * 4);
  10785. }
  10786. // Convert each pixel.
  10787. for (var x = 0; x < width; x++) {
  10788. for (var y = 0; y < height; y++) {
  10789. var index = (y * width + x) * 3;
  10790. var newIndex = (y * width + x) * 4;
  10791. // Map Old Value to new value.
  10792. rgbaData[newIndex + 0] = rgbData[index + 0];
  10793. rgbaData[newIndex + 1] = rgbData[index + 1];
  10794. rgbaData[newIndex + 2] = rgbData[index + 2];
  10795. // Add fully opaque alpha channel.
  10796. rgbaData[newIndex + 3] = 1;
  10797. }
  10798. }
  10799. return rgbaData;
  10800. };
  10801. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10802. var gl = this._gl;
  10803. if (texture._framebuffer) {
  10804. gl.deleteFramebuffer(texture._framebuffer);
  10805. texture._framebuffer = null;
  10806. }
  10807. if (texture._depthStencilBuffer) {
  10808. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10809. texture._depthStencilBuffer = null;
  10810. }
  10811. if (texture._MSAAFramebuffer) {
  10812. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10813. texture._MSAAFramebuffer = null;
  10814. }
  10815. if (texture._MSAARenderBuffer) {
  10816. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10817. texture._MSAARenderBuffer = null;
  10818. }
  10819. };
  10820. Engine.prototype._releaseTexture = function (texture) {
  10821. var gl = this._gl;
  10822. this._releaseFramebufferObjects(texture);
  10823. gl.deleteTexture(texture._webGLTexture);
  10824. // Unbind channels
  10825. this.unbindAllTextures();
  10826. var index = this._internalTexturesCache.indexOf(texture);
  10827. if (index !== -1) {
  10828. this._internalTexturesCache.splice(index, 1);
  10829. }
  10830. // Integrated fixed lod samplers.
  10831. if (texture._lodTextureHigh) {
  10832. texture._lodTextureHigh.dispose();
  10833. }
  10834. if (texture._lodTextureMid) {
  10835. texture._lodTextureMid.dispose();
  10836. }
  10837. if (texture._lodTextureLow) {
  10838. texture._lodTextureLow.dispose();
  10839. }
  10840. };
  10841. Engine.prototype.setProgram = function (program) {
  10842. if (this._currentProgram !== program) {
  10843. this._gl.useProgram(program);
  10844. this._currentProgram = program;
  10845. }
  10846. };
  10847. Engine.prototype.bindSamplers = function (effect) {
  10848. this.setProgram(effect.getProgram());
  10849. var samplers = effect.getSamplers();
  10850. for (var index = 0; index < samplers.length; index++) {
  10851. var uniform = effect.getUniform(samplers[index]);
  10852. this._gl.uniform1i(uniform, index);
  10853. }
  10854. this._currentEffect = null;
  10855. };
  10856. Engine.prototype.activateTexture = function (texture) {
  10857. if (this._activeTexture !== texture) {
  10858. this._gl.activeTexture(texture);
  10859. this._activeTexture = texture;
  10860. }
  10861. };
  10862. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10863. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10864. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10865. this._activeTexturesCache[this._activeTexture] = texture;
  10866. }
  10867. };
  10868. Engine.prototype._bindTexture = function (channel, texture) {
  10869. if (channel < 0) {
  10870. return;
  10871. }
  10872. this.activateTexture(this._gl.TEXTURE0 + channel);
  10873. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10874. };
  10875. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10876. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10877. };
  10878. Engine.prototype.unbindAllTextures = function () {
  10879. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10880. this.activateTexture(this._gl["TEXTURE" + channel]);
  10881. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10882. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10883. }
  10884. };
  10885. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10886. if (channel < 0) {
  10887. return;
  10888. }
  10889. this._gl.uniform1i(uniform, channel);
  10890. this._setTexture(channel, texture);
  10891. };
  10892. Engine.prototype._setTexture = function (channel, texture) {
  10893. // Not ready?
  10894. if (!texture) {
  10895. if (this._activeTexturesCache[channel] != null) {
  10896. this.activateTexture(this._gl["TEXTURE" + channel]);
  10897. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10898. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10899. }
  10900. return;
  10901. }
  10902. // Video
  10903. var alreadyActivated = false;
  10904. if (texture.video) {
  10905. this.activateTexture(this._gl["TEXTURE" + channel]);
  10906. alreadyActivated = true;
  10907. texture.update();
  10908. }
  10909. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10910. texture.delayLoad();
  10911. return;
  10912. }
  10913. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10914. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10915. if (this._activeTexturesCache[channel] === internalTexture) {
  10916. return;
  10917. }
  10918. if (!alreadyActivated) {
  10919. this.activateTexture(this._gl["TEXTURE" + channel]);
  10920. }
  10921. if (internalTexture.isCube) {
  10922. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10923. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10924. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10925. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10926. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10927. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10928. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10929. }
  10930. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10931. }
  10932. else {
  10933. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10934. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10935. internalTexture._cachedWrapU = texture.wrapU;
  10936. switch (texture.wrapU) {
  10937. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10938. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10939. break;
  10940. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10941. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10942. break;
  10943. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10944. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10945. break;
  10946. }
  10947. }
  10948. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10949. internalTexture._cachedWrapV = texture.wrapV;
  10950. switch (texture.wrapV) {
  10951. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10952. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10953. break;
  10954. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10955. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10956. break;
  10957. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10958. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10959. break;
  10960. }
  10961. }
  10962. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10963. }
  10964. };
  10965. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10966. if (channel < 0) {
  10967. return;
  10968. }
  10969. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10970. this._textureUnits = new Int32Array(textures.length);
  10971. }
  10972. for (var i = 0; i < textures.length; i++) {
  10973. this._textureUnits[i] = channel + i;
  10974. }
  10975. this._gl.uniform1iv(uniform, this._textureUnits);
  10976. for (var index = 0; index < textures.length; index++) {
  10977. this._setTexture(channel + index, textures[index]);
  10978. }
  10979. };
  10980. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10981. var internalTexture = texture.getInternalTexture();
  10982. if (!internalTexture) {
  10983. return;
  10984. }
  10985. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10986. var value = texture.anisotropicFilteringLevel;
  10987. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  10988. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  10989. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  10990. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  10991. }
  10992. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10993. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10994. internalTexture._cachedAnisotropicFilteringLevel = value;
  10995. }
  10996. };
  10997. Engine.prototype.readPixels = function (x, y, width, height) {
  10998. var data = new Uint8Array(height * width * 4);
  10999. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11000. return data;
  11001. };
  11002. /**
  11003. * Add an externaly attached data from its key.
  11004. * This method call will fail and return false, if such key already exists.
  11005. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11006. * @param key the unique key that identifies the data
  11007. * @param data the data object to associate to the key for this Engine instance
  11008. * @return true if no such key were already present and the data was added successfully, false otherwise
  11009. */
  11010. Engine.prototype.addExternalData = function (key, data) {
  11011. if (!this._externalData) {
  11012. this._externalData = new BABYLON.StringDictionary();
  11013. }
  11014. return this._externalData.add(key, data);
  11015. };
  11016. /**
  11017. * Get an externaly attached data from its key
  11018. * @param key the unique key that identifies the data
  11019. * @return the associated data, if present (can be null), or undefined if not present
  11020. */
  11021. Engine.prototype.getExternalData = function (key) {
  11022. if (!this._externalData) {
  11023. this._externalData = new BABYLON.StringDictionary();
  11024. }
  11025. return this._externalData.get(key);
  11026. };
  11027. /**
  11028. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11029. * @param key the unique key that identifies the data
  11030. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11031. * @return the associated data, can be null if the factory returned null.
  11032. */
  11033. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11034. if (!this._externalData) {
  11035. this._externalData = new BABYLON.StringDictionary();
  11036. }
  11037. return this._externalData.getOrAddWithFactory(key, factory);
  11038. };
  11039. /**
  11040. * Remove an externaly attached data from the Engine instance
  11041. * @param key the unique key that identifies the data
  11042. * @return true if the data was successfully removed, false if it doesn't exist
  11043. */
  11044. Engine.prototype.removeExternalData = function (key) {
  11045. if (!this._externalData) {
  11046. this._externalData = new BABYLON.StringDictionary();
  11047. }
  11048. return this._externalData.remove(key);
  11049. };
  11050. Engine.prototype.unbindAllAttributes = function () {
  11051. if (this._mustWipeVertexAttributes) {
  11052. this._mustWipeVertexAttributes = false;
  11053. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11054. this._gl.disableVertexAttribArray(i);
  11055. this._vertexAttribArraysEnabled[i] = false;
  11056. this._currentBufferPointers[i].active = false;
  11057. }
  11058. return;
  11059. }
  11060. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11061. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11062. continue;
  11063. }
  11064. this._gl.disableVertexAttribArray(i);
  11065. this._vertexAttribArraysEnabled[i] = false;
  11066. this._currentBufferPointers[i].active = false;
  11067. }
  11068. };
  11069. Engine.prototype.releaseEffects = function () {
  11070. for (var name in this._compiledEffects) {
  11071. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11072. }
  11073. this._compiledEffects = {};
  11074. };
  11075. // Dispose
  11076. Engine.prototype.dispose = function () {
  11077. this.hideLoadingUI();
  11078. this.stopRenderLoop();
  11079. // Release postProcesses
  11080. while (this.postProcesses.length) {
  11081. this.postProcesses[0].dispose();
  11082. }
  11083. // Empty texture
  11084. if (this._emptyTexture) {
  11085. this._releaseTexture(this._emptyTexture);
  11086. this._emptyTexture = null;
  11087. }
  11088. if (this._emptyCubeTexture) {
  11089. this._releaseTexture(this._emptyCubeTexture);
  11090. this._emptyCubeTexture = null;
  11091. }
  11092. // Rescale PP
  11093. if (this._rescalePostProcess) {
  11094. this._rescalePostProcess.dispose();
  11095. }
  11096. // Release scenes
  11097. while (this.scenes.length) {
  11098. this.scenes[0].dispose();
  11099. }
  11100. // Release audio engine
  11101. if (Engine.audioEngine) {
  11102. Engine.audioEngine.dispose();
  11103. }
  11104. // Release effects
  11105. this.releaseEffects();
  11106. // Unbind
  11107. this.unbindAllAttributes();
  11108. if (this._dummyFramebuffer) {
  11109. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11110. }
  11111. this._gl = null;
  11112. //WebVR
  11113. this.disableVR();
  11114. // Events
  11115. window.removeEventListener("blur", this._onBlur);
  11116. window.removeEventListener("focus", this._onFocus);
  11117. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11118. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11119. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11120. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11121. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11122. if (!this._doNotHandleContextLost) {
  11123. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11124. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11125. }
  11126. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11127. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11128. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11129. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11130. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11131. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11132. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11133. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11134. // Remove from Instances
  11135. var index = Engine.Instances.indexOf(this);
  11136. if (index >= 0) {
  11137. Engine.Instances.splice(index, 1);
  11138. }
  11139. this._workingCanvas = null;
  11140. this._workingContext = null;
  11141. this._currentBufferPointers = null;
  11142. this._renderingCanvas = null;
  11143. this._currentProgram = null;
  11144. this.onResizeObservable.clear();
  11145. this.onCanvasBlurObservable.clear();
  11146. this.onCanvasFocusObservable.clear();
  11147. this.onCanvasPointerOutObservable.clear();
  11148. BABYLON.Effect.ResetCache();
  11149. };
  11150. // Loading screen
  11151. Engine.prototype.displayLoadingUI = function () {
  11152. var loadingScreen = this.loadingScreen;
  11153. if (loadingScreen) {
  11154. loadingScreen.displayLoadingUI();
  11155. }
  11156. };
  11157. Engine.prototype.hideLoadingUI = function () {
  11158. var loadingScreen = this.loadingScreen;
  11159. if (loadingScreen) {
  11160. loadingScreen.hideLoadingUI();
  11161. }
  11162. };
  11163. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11164. get: function () {
  11165. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11166. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11167. return this._loadingScreen;
  11168. },
  11169. set: function (loadingScreen) {
  11170. this._loadingScreen = loadingScreen;
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11176. set: function (text) {
  11177. this.loadingScreen.loadingUIText = text;
  11178. },
  11179. enumerable: true,
  11180. configurable: true
  11181. });
  11182. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11183. set: function (color) {
  11184. this.loadingScreen.loadingUIBackgroundColor = color;
  11185. },
  11186. enumerable: true,
  11187. configurable: true
  11188. });
  11189. Engine.prototype.attachContextLostEvent = function (callback) {
  11190. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11191. };
  11192. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11193. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11194. };
  11195. Engine.prototype.getVertexShaderSource = function (program) {
  11196. var shaders = this._gl.getAttachedShaders(program);
  11197. return this._gl.getShaderSource(shaders[0]);
  11198. };
  11199. Engine.prototype.getFragmentShaderSource = function (program) {
  11200. var shaders = this._gl.getAttachedShaders(program);
  11201. return this._gl.getShaderSource(shaders[1]);
  11202. };
  11203. Engine.prototype.getError = function () {
  11204. return this._gl.getError();
  11205. };
  11206. // FPS
  11207. Engine.prototype.getFps = function () {
  11208. return this._fps;
  11209. };
  11210. Engine.prototype.getDeltaTime = function () {
  11211. return this._deltaTime;
  11212. };
  11213. Engine.prototype._measureFps = function () {
  11214. this._performanceMonitor.sampleFrame();
  11215. this._fps = this._performanceMonitor.averageFPS;
  11216. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11217. };
  11218. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11219. if (faceIndex === void 0) { faceIndex = -1; }
  11220. var gl = this._gl;
  11221. if (!this._dummyFramebuffer) {
  11222. this._dummyFramebuffer = gl.createFramebuffer();
  11223. }
  11224. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11225. if (faceIndex > -1) {
  11226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11227. }
  11228. else {
  11229. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11230. }
  11231. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11232. var buffer;
  11233. switch (readType) {
  11234. case gl.UNSIGNED_BYTE:
  11235. buffer = new Uint8Array(4 * width * height);
  11236. readType = gl.UNSIGNED_BYTE;
  11237. break;
  11238. default:
  11239. buffer = new Float32Array(4 * width * height);
  11240. readType = gl.FLOAT;
  11241. break;
  11242. }
  11243. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11244. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11245. return buffer;
  11246. };
  11247. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11248. if (this._webGLVersion > 1) {
  11249. return this._caps.colorBufferFloat;
  11250. }
  11251. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11252. };
  11253. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11254. if (this._webGLVersion > 1) {
  11255. return this._caps.colorBufferFloat;
  11256. }
  11257. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11258. };
  11259. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11260. Engine.prototype._canRenderToFramebuffer = function (type) {
  11261. var gl = this._gl;
  11262. //clear existing errors
  11263. while (gl.getError() !== gl.NO_ERROR) { }
  11264. var successful = true;
  11265. var texture = gl.createTexture();
  11266. gl.bindTexture(gl.TEXTURE_2D, texture);
  11267. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11270. var fb = gl.createFramebuffer();
  11271. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11272. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11273. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11274. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11275. successful = successful && (gl.getError() === gl.NO_ERROR);
  11276. //try render by clearing frame buffer's color buffer
  11277. if (successful) {
  11278. gl.clear(gl.COLOR_BUFFER_BIT);
  11279. successful = successful && (gl.getError() === gl.NO_ERROR);
  11280. }
  11281. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11282. if (successful) {
  11283. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11284. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11285. var readFormat = gl.RGBA;
  11286. var readType = gl.UNSIGNED_BYTE;
  11287. var buffer = new Uint8Array(4);
  11288. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11289. successful = successful && (gl.getError() === gl.NO_ERROR);
  11290. }
  11291. //clean up
  11292. gl.deleteTexture(texture);
  11293. gl.deleteFramebuffer(fb);
  11294. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11295. //clear accumulated errors
  11296. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11297. return successful;
  11298. };
  11299. Engine.prototype._getWebGLTextureType = function (type) {
  11300. if (type === Engine.TEXTURETYPE_FLOAT) {
  11301. return this._gl.FLOAT;
  11302. }
  11303. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11304. // Add Half Float Constant.
  11305. return this._gl.HALF_FLOAT_OES;
  11306. }
  11307. return this._gl.UNSIGNED_BYTE;
  11308. };
  11309. ;
  11310. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11311. if (this._webGLVersion === 1) {
  11312. return this._gl.RGBA;
  11313. }
  11314. if (type === Engine.TEXTURETYPE_FLOAT) {
  11315. return this._gl.RGBA32F;
  11316. }
  11317. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11318. return this._gl.RGBA16F;
  11319. }
  11320. return this._gl.RGBA;
  11321. };
  11322. ;
  11323. Engine.prototype.createQuery = function () {
  11324. return this._gl.createQuery();
  11325. };
  11326. Engine.prototype.deleteQuery = function (query) {
  11327. this._gl.deleteQuery(query);
  11328. return this;
  11329. };
  11330. Engine.prototype.isQueryResultAvailable = function (query) {
  11331. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11332. };
  11333. Engine.prototype.getQueryResult = function (query) {
  11334. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11335. };
  11336. Engine.prototype.beginQuery = function (algorithmType, query) {
  11337. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11338. this._gl.beginQuery(glAlgorithm, query);
  11339. };
  11340. Engine.prototype.endQuery = function (algorithmType) {
  11341. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11342. this._gl.endQuery(glAlgorithm);
  11343. return this;
  11344. };
  11345. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11346. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11347. };
  11348. // Statics
  11349. Engine.isSupported = function () {
  11350. try {
  11351. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11352. if (navigator.isCocoonJS) {
  11353. return true;
  11354. }
  11355. var tempcanvas = document.createElement("canvas");
  11356. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11357. return gl != null && !!window.WebGLRenderingContext;
  11358. }
  11359. catch (e) {
  11360. return false;
  11361. }
  11362. };
  11363. Engine.Instances = new Array();
  11364. // Const statics
  11365. Engine._ALPHA_DISABLE = 0;
  11366. Engine._ALPHA_ADD = 1;
  11367. Engine._ALPHA_COMBINE = 2;
  11368. Engine._ALPHA_SUBTRACT = 3;
  11369. Engine._ALPHA_MULTIPLY = 4;
  11370. Engine._ALPHA_MAXIMIZED = 5;
  11371. Engine._ALPHA_ONEONE = 6;
  11372. Engine._ALPHA_PREMULTIPLIED = 7;
  11373. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11374. Engine._ALPHA_INTERPOLATE = 9;
  11375. Engine._ALPHA_SCREENMODE = 10;
  11376. Engine._DELAYLOADSTATE_NONE = 0;
  11377. Engine._DELAYLOADSTATE_LOADED = 1;
  11378. Engine._DELAYLOADSTATE_LOADING = 2;
  11379. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11380. Engine._TEXTUREFORMAT_ALPHA = 0;
  11381. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11382. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11383. Engine._TEXTUREFORMAT_RGB = 4;
  11384. Engine._TEXTUREFORMAT_RGBA = 5;
  11385. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11386. Engine._TEXTURETYPE_FLOAT = 1;
  11387. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11388. // Depht or Stencil test Constants.
  11389. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11390. 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.
  11391. 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.
  11392. 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.
  11393. 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.
  11394. 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.
  11395. 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.
  11396. 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.
  11397. // Stencil Actions Constants.
  11398. Engine._KEEP = 0x1E00;
  11399. Engine._REPLACE = 0x1E01;
  11400. Engine._INCR = 0x1E02;
  11401. Engine._DECR = 0x1E03;
  11402. Engine._INVERT = 0x150A;
  11403. Engine._INCR_WRAP = 0x8507;
  11404. Engine._DECR_WRAP = 0x8508;
  11405. // Texture rescaling mode
  11406. Engine._SCALEMODE_FLOOR = 1;
  11407. Engine._SCALEMODE_NEAREST = 2;
  11408. Engine._SCALEMODE_CEILING = 3;
  11409. // Updatable statics so stick with vars here
  11410. Engine.CollisionsEpsilon = 0.001;
  11411. Engine.CodeRepository = "src/";
  11412. Engine.ShadersRepository = "src/Shaders/";
  11413. return Engine;
  11414. }());
  11415. BABYLON.Engine = Engine;
  11416. })(BABYLON || (BABYLON = {}));
  11417. //# sourceMappingURL=babylon.engine.js.map
  11418. /// <reference path="Tools\babylon.decorators.ts" />
  11419. var BABYLON;
  11420. (function (BABYLON) {
  11421. /**
  11422. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11423. */
  11424. var Node = (function () {
  11425. /**
  11426. * @constructor
  11427. * @param {string} name - the name and id to be given to this node
  11428. * @param {BABYLON.Scene} the scene this node will be added to
  11429. */
  11430. function Node(name, scene) {
  11431. this.state = "";
  11432. this.metadata = null;
  11433. this.doNotSerialize = false;
  11434. this.animations = new Array();
  11435. this._ranges = {};
  11436. this._childrenFlag = -1;
  11437. this._isEnabled = true;
  11438. this._isReady = true;
  11439. this._currentRenderId = -1;
  11440. this._parentRenderId = -1;
  11441. /**
  11442. * An event triggered when the mesh is disposed.
  11443. * @type {BABYLON.Observable}
  11444. */
  11445. this.onDisposeObservable = new BABYLON.Observable();
  11446. // Behaviors
  11447. this._behaviors = new Array();
  11448. this.name = name;
  11449. this.id = name;
  11450. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11451. this._initCache();
  11452. }
  11453. Object.defineProperty(Node.prototype, "parent", {
  11454. get: function () {
  11455. return this._parentNode;
  11456. },
  11457. set: function (parent) {
  11458. if (this._parentNode === parent) {
  11459. return;
  11460. }
  11461. if (this._parentNode) {
  11462. var index = this._parentNode._children.indexOf(this);
  11463. if (index !== -1) {
  11464. this._parentNode._children.splice(index, 1);
  11465. }
  11466. }
  11467. this._parentNode = parent;
  11468. if (this._parentNode) {
  11469. if (!this._parentNode._children) {
  11470. this._parentNode._children = new Array();
  11471. }
  11472. this._parentNode._children.push(this);
  11473. }
  11474. },
  11475. enumerable: true,
  11476. configurable: true
  11477. });
  11478. Node.prototype.getClassName = function () {
  11479. return "Node";
  11480. };
  11481. Object.defineProperty(Node.prototype, "onDispose", {
  11482. set: function (callback) {
  11483. if (this._onDisposeObserver) {
  11484. this.onDisposeObservable.remove(this._onDisposeObserver);
  11485. }
  11486. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11487. },
  11488. enumerable: true,
  11489. configurable: true
  11490. });
  11491. Node.prototype.getScene = function () {
  11492. return this._scene;
  11493. };
  11494. Node.prototype.getEngine = function () {
  11495. return this._scene.getEngine();
  11496. };
  11497. Node.prototype.addBehavior = function (behavior) {
  11498. var index = this._behaviors.indexOf(behavior);
  11499. if (index !== -1) {
  11500. return;
  11501. }
  11502. behavior.attach(this);
  11503. this._behaviors.push(behavior);
  11504. return this;
  11505. };
  11506. Node.prototype.removeBehavior = function (behavior) {
  11507. var index = this._behaviors.indexOf(behavior);
  11508. if (index === -1) {
  11509. return;
  11510. }
  11511. this._behaviors[index].detach();
  11512. this._behaviors.splice(index, 1);
  11513. return this;
  11514. };
  11515. Object.defineProperty(Node.prototype, "behaviors", {
  11516. get: function () {
  11517. return this._behaviors;
  11518. },
  11519. enumerable: true,
  11520. configurable: true
  11521. });
  11522. Node.prototype.getBehaviorByName = function (name) {
  11523. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11524. var behavior = _a[_i];
  11525. if (behavior.name === name) {
  11526. return behavior;
  11527. }
  11528. }
  11529. return null;
  11530. };
  11531. // override it in derived class
  11532. Node.prototype.getWorldMatrix = function () {
  11533. return BABYLON.Matrix.Identity();
  11534. };
  11535. // override it in derived class if you add new variables to the cache
  11536. // and call the parent class method
  11537. Node.prototype._initCache = function () {
  11538. this._cache = {};
  11539. this._cache.parent = undefined;
  11540. };
  11541. Node.prototype.updateCache = function (force) {
  11542. if (!force && this.isSynchronized())
  11543. return;
  11544. this._cache.parent = this.parent;
  11545. this._updateCache();
  11546. };
  11547. // override it in derived class if you add new variables to the cache
  11548. // and call the parent class method if !ignoreParentClass
  11549. Node.prototype._updateCache = function (ignoreParentClass) {
  11550. };
  11551. // override it in derived class if you add new variables to the cache
  11552. Node.prototype._isSynchronized = function () {
  11553. return true;
  11554. };
  11555. Node.prototype._markSyncedWithParent = function () {
  11556. this._parentRenderId = this.parent._currentRenderId;
  11557. };
  11558. Node.prototype.isSynchronizedWithParent = function () {
  11559. if (!this.parent) {
  11560. return true;
  11561. }
  11562. if (this._parentRenderId !== this.parent._currentRenderId) {
  11563. return false;
  11564. }
  11565. return this.parent.isSynchronized();
  11566. };
  11567. Node.prototype.isSynchronized = function (updateCache) {
  11568. var check = this.hasNewParent();
  11569. check = check || !this.isSynchronizedWithParent();
  11570. check = check || !this._isSynchronized();
  11571. if (updateCache)
  11572. this.updateCache(true);
  11573. return !check;
  11574. };
  11575. Node.prototype.hasNewParent = function (update) {
  11576. if (this._cache.parent === this.parent)
  11577. return false;
  11578. if (update)
  11579. this._cache.parent = this.parent;
  11580. return true;
  11581. };
  11582. /**
  11583. * Is this node ready to be used/rendered
  11584. * @return {boolean} is it ready
  11585. */
  11586. Node.prototype.isReady = function () {
  11587. return this._isReady;
  11588. };
  11589. /**
  11590. * Is this node enabled.
  11591. * If the node has a parent and is enabled, the parent will be inspected as well.
  11592. * @return {boolean} whether this node (and its parent) is enabled.
  11593. * @see setEnabled
  11594. */
  11595. Node.prototype.isEnabled = function () {
  11596. if (!this._isEnabled) {
  11597. return false;
  11598. }
  11599. if (this.parent) {
  11600. return this.parent.isEnabled();
  11601. }
  11602. return true;
  11603. };
  11604. /**
  11605. * Set the enabled state of this node.
  11606. * @param {boolean} value - the new enabled state
  11607. * @see isEnabled
  11608. */
  11609. Node.prototype.setEnabled = function (value) {
  11610. this._isEnabled = value;
  11611. };
  11612. /**
  11613. * Is this node a descendant of the given node.
  11614. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11615. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11616. * @see parent
  11617. */
  11618. Node.prototype.isDescendantOf = function (ancestor) {
  11619. if (this.parent) {
  11620. if (this.parent === ancestor) {
  11621. return true;
  11622. }
  11623. return this.parent.isDescendantOf(ancestor);
  11624. }
  11625. return false;
  11626. };
  11627. /**
  11628. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11629. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11630. * @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.
  11631. * @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.
  11632. */
  11633. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11634. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11635. if (!this._children) {
  11636. return;
  11637. }
  11638. for (var index = 0; index < this._children.length; index++) {
  11639. var item = this._children[index];
  11640. if (!predicate || predicate(item)) {
  11641. results.push(item);
  11642. }
  11643. if (!directDescendantsOnly) {
  11644. item._getDescendants(results, false, predicate);
  11645. }
  11646. }
  11647. };
  11648. /**
  11649. * Will return all nodes that have this node as ascendant.
  11650. * @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.
  11651. * @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.
  11652. * @return {BABYLON.Node[]} all children nodes of all types.
  11653. */
  11654. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11655. var results = [];
  11656. this._getDescendants(results, directDescendantsOnly, predicate);
  11657. return results;
  11658. };
  11659. /**
  11660. * Get all child-meshes of this node.
  11661. */
  11662. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11663. var results = [];
  11664. this._getDescendants(results, directDecendantsOnly, function (node) {
  11665. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11666. });
  11667. return results;
  11668. };
  11669. /**
  11670. * Get all direct children of this node.
  11671. */
  11672. Node.prototype.getChildren = function (predicate) {
  11673. return this.getDescendants(true, predicate);
  11674. };
  11675. Node.prototype._setReady = function (state) {
  11676. if (state === this._isReady) {
  11677. return;
  11678. }
  11679. if (!state) {
  11680. this._isReady = false;
  11681. return;
  11682. }
  11683. this._isReady = true;
  11684. if (this.onReady) {
  11685. this.onReady(this);
  11686. }
  11687. };
  11688. Node.prototype.getAnimationByName = function (name) {
  11689. for (var i = 0; i < this.animations.length; i++) {
  11690. var animation = this.animations[i];
  11691. if (animation.name === name) {
  11692. return animation;
  11693. }
  11694. }
  11695. return null;
  11696. };
  11697. Node.prototype.createAnimationRange = function (name, from, to) {
  11698. // check name not already in use
  11699. if (!this._ranges[name]) {
  11700. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11701. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11702. if (this.animations[i]) {
  11703. this.animations[i].createRange(name, from, to);
  11704. }
  11705. }
  11706. }
  11707. };
  11708. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11709. if (deleteFrames === void 0) { deleteFrames = true; }
  11710. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11711. if (this.animations[i]) {
  11712. this.animations[i].deleteRange(name, deleteFrames);
  11713. }
  11714. }
  11715. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11716. };
  11717. Node.prototype.getAnimationRange = function (name) {
  11718. return this._ranges[name];
  11719. };
  11720. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11721. var range = this.getAnimationRange(name);
  11722. if (!range) {
  11723. return null;
  11724. }
  11725. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11726. };
  11727. Node.prototype.serializeAnimationRanges = function () {
  11728. var serializationRanges = [];
  11729. for (var name in this._ranges) {
  11730. var range = {};
  11731. range.name = name;
  11732. range.from = this._ranges[name].from;
  11733. range.to = this._ranges[name].to;
  11734. serializationRanges.push(range);
  11735. }
  11736. return serializationRanges;
  11737. };
  11738. Node.prototype.dispose = function () {
  11739. this.parent = null;
  11740. // Callback
  11741. this.onDisposeObservable.notifyObservers(this);
  11742. this.onDisposeObservable.clear();
  11743. // Behaviors
  11744. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11745. var behavior = _a[_i];
  11746. behavior.detach();
  11747. }
  11748. this._behaviors = [];
  11749. };
  11750. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11751. if (parsedNode.ranges) {
  11752. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11753. var data = parsedNode.ranges[index];
  11754. node.createAnimationRange(data.name, data.from, data.to);
  11755. }
  11756. }
  11757. };
  11758. __decorate([
  11759. BABYLON.serialize()
  11760. ], Node.prototype, "name", void 0);
  11761. __decorate([
  11762. BABYLON.serialize()
  11763. ], Node.prototype, "id", void 0);
  11764. __decorate([
  11765. BABYLON.serialize()
  11766. ], Node.prototype, "uniqueId", void 0);
  11767. __decorate([
  11768. BABYLON.serialize()
  11769. ], Node.prototype, "state", void 0);
  11770. __decorate([
  11771. BABYLON.serialize()
  11772. ], Node.prototype, "metadata", void 0);
  11773. return Node;
  11774. }());
  11775. BABYLON.Node = Node;
  11776. })(BABYLON || (BABYLON = {}));
  11777. //# sourceMappingURL=babylon.node.js.map
  11778. var BABYLON;
  11779. (function (BABYLON) {
  11780. var BoundingSphere = (function () {
  11781. function BoundingSphere(minimum, maximum) {
  11782. this.minimum = minimum;
  11783. this.maximum = maximum;
  11784. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11785. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11786. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11787. this.radius = distance * 0.5;
  11788. this.centerWorld = BABYLON.Vector3.Zero();
  11789. this._update(BABYLON.Matrix.Identity());
  11790. }
  11791. // Methods
  11792. BoundingSphere.prototype._update = function (world) {
  11793. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11794. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11795. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11796. };
  11797. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11798. for (var i = 0; i < 6; i++) {
  11799. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11800. return false;
  11801. }
  11802. return true;
  11803. };
  11804. BoundingSphere.prototype.intersectsPoint = function (point) {
  11805. var x = this.centerWorld.x - point.x;
  11806. var y = this.centerWorld.y - point.y;
  11807. var z = this.centerWorld.z - point.z;
  11808. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11809. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11810. return false;
  11811. return true;
  11812. };
  11813. // Statics
  11814. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11815. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11816. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11817. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11818. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11819. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11820. return false;
  11821. return true;
  11822. };
  11823. return BoundingSphere;
  11824. }());
  11825. BABYLON.BoundingSphere = BoundingSphere;
  11826. })(BABYLON || (BABYLON = {}));
  11827. //# sourceMappingURL=babylon.boundingSphere.js.map
  11828. var BABYLON;
  11829. (function (BABYLON) {
  11830. var BoundingBox = (function () {
  11831. function BoundingBox(minimum, maximum) {
  11832. this.minimum = minimum;
  11833. this.maximum = maximum;
  11834. this.vectors = new Array();
  11835. this.vectorsWorld = new Array();
  11836. // Bounding vectors
  11837. this.vectors.push(this.minimum.clone());
  11838. this.vectors.push(this.maximum.clone());
  11839. this.vectors.push(this.minimum.clone());
  11840. this.vectors[2].x = this.maximum.x;
  11841. this.vectors.push(this.minimum.clone());
  11842. this.vectors[3].y = this.maximum.y;
  11843. this.vectors.push(this.minimum.clone());
  11844. this.vectors[4].z = this.maximum.z;
  11845. this.vectors.push(this.maximum.clone());
  11846. this.vectors[5].z = this.minimum.z;
  11847. this.vectors.push(this.maximum.clone());
  11848. this.vectors[6].x = this.minimum.x;
  11849. this.vectors.push(this.maximum.clone());
  11850. this.vectors[7].y = this.minimum.y;
  11851. // OBB
  11852. this.center = this.maximum.add(this.minimum).scale(0.5);
  11853. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11854. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11855. // World
  11856. for (var index = 0; index < this.vectors.length; index++) {
  11857. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11858. }
  11859. this.minimumWorld = BABYLON.Vector3.Zero();
  11860. this.maximumWorld = BABYLON.Vector3.Zero();
  11861. this.centerWorld = BABYLON.Vector3.Zero();
  11862. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11863. this._update(BABYLON.Matrix.Identity());
  11864. }
  11865. // Methods
  11866. BoundingBox.prototype.getWorldMatrix = function () {
  11867. return this._worldMatrix;
  11868. };
  11869. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11870. this._worldMatrix.copyFrom(matrix);
  11871. return this;
  11872. };
  11873. BoundingBox.prototype._update = function (world) {
  11874. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11875. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11876. for (var index = 0; index < this.vectors.length; index++) {
  11877. var v = this.vectorsWorld[index];
  11878. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11879. if (v.x < this.minimumWorld.x)
  11880. this.minimumWorld.x = v.x;
  11881. if (v.y < this.minimumWorld.y)
  11882. this.minimumWorld.y = v.y;
  11883. if (v.z < this.minimumWorld.z)
  11884. this.minimumWorld.z = v.z;
  11885. if (v.x > this.maximumWorld.x)
  11886. this.maximumWorld.x = v.x;
  11887. if (v.y > this.maximumWorld.y)
  11888. this.maximumWorld.y = v.y;
  11889. if (v.z > this.maximumWorld.z)
  11890. this.maximumWorld.z = v.z;
  11891. }
  11892. // Extend
  11893. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11894. this.extendSizeWorld.scaleInPlace(0.5);
  11895. // OBB
  11896. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11897. this.centerWorld.scaleInPlace(0.5);
  11898. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11899. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11900. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11901. this._worldMatrix = world;
  11902. };
  11903. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11904. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11905. };
  11906. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11907. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11908. };
  11909. BoundingBox.prototype.intersectsPoint = function (point) {
  11910. var delta = -BABYLON.Epsilon;
  11911. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11912. return false;
  11913. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11914. return false;
  11915. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11916. return false;
  11917. return true;
  11918. };
  11919. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11920. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11921. };
  11922. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11923. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11924. return false;
  11925. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11926. return false;
  11927. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11928. return false;
  11929. return true;
  11930. };
  11931. // Statics
  11932. BoundingBox.Intersects = function (box0, box1) {
  11933. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11934. return false;
  11935. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11936. return false;
  11937. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11938. return false;
  11939. return true;
  11940. };
  11941. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11942. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11943. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11944. return (num <= (sphereRadius * sphereRadius));
  11945. };
  11946. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11947. for (var p = 0; p < 6; p++) {
  11948. for (var i = 0; i < 8; i++) {
  11949. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11950. return false;
  11951. }
  11952. }
  11953. }
  11954. return true;
  11955. };
  11956. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11957. for (var p = 0; p < 6; p++) {
  11958. var inCount = 8;
  11959. for (var i = 0; i < 8; i++) {
  11960. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11961. --inCount;
  11962. }
  11963. else {
  11964. break;
  11965. }
  11966. }
  11967. if (inCount === 0)
  11968. return false;
  11969. }
  11970. return true;
  11971. };
  11972. return BoundingBox;
  11973. }());
  11974. BABYLON.BoundingBox = BoundingBox;
  11975. })(BABYLON || (BABYLON = {}));
  11976. //# sourceMappingURL=babylon.boundingBox.js.map
  11977. var BABYLON;
  11978. (function (BABYLON) {
  11979. var computeBoxExtents = function (axis, box) {
  11980. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11981. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11982. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11983. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11984. var r = r0 + r1 + r2;
  11985. return {
  11986. min: p - r,
  11987. max: p + r
  11988. };
  11989. };
  11990. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11991. var axisOverlap = function (axis, box0, box1) {
  11992. var result0 = computeBoxExtents(axis, box0);
  11993. var result1 = computeBoxExtents(axis, box1);
  11994. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11995. };
  11996. var BoundingInfo = (function () {
  11997. function BoundingInfo(minimum, maximum) {
  11998. this.minimum = minimum;
  11999. this.maximum = maximum;
  12000. this._isLocked = false;
  12001. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12002. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12003. }
  12004. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12005. get: function () {
  12006. return this._isLocked;
  12007. },
  12008. set: function (value) {
  12009. this._isLocked = value;
  12010. },
  12011. enumerable: true,
  12012. configurable: true
  12013. });
  12014. // Methods
  12015. BoundingInfo.prototype.update = function (world) {
  12016. if (this._isLocked) {
  12017. return;
  12018. }
  12019. this.boundingBox._update(world);
  12020. this.boundingSphere._update(world);
  12021. };
  12022. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12023. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12024. return false;
  12025. return this.boundingBox.isInFrustum(frustumPlanes);
  12026. };
  12027. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12028. /**
  12029. * Gets the world distance between the min and max points of the bounding box
  12030. */
  12031. get: function () {
  12032. var boundingBox = this.boundingBox;
  12033. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12034. return size.length();
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12040. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12041. };
  12042. BoundingInfo.prototype._checkCollision = function (collider) {
  12043. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12044. };
  12045. BoundingInfo.prototype.intersectsPoint = function (point) {
  12046. if (!this.boundingSphere.centerWorld) {
  12047. return false;
  12048. }
  12049. if (!this.boundingSphere.intersectsPoint(point)) {
  12050. return false;
  12051. }
  12052. if (!this.boundingBox.intersectsPoint(point)) {
  12053. return false;
  12054. }
  12055. return true;
  12056. };
  12057. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12058. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12059. return false;
  12060. }
  12061. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12062. return false;
  12063. }
  12064. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12065. return false;
  12066. }
  12067. if (!precise) {
  12068. return true;
  12069. }
  12070. var box0 = this.boundingBox;
  12071. var box1 = boundingInfo.boundingBox;
  12072. if (!axisOverlap(box0.directions[0], box0, box1))
  12073. return false;
  12074. if (!axisOverlap(box0.directions[1], box0, box1))
  12075. return false;
  12076. if (!axisOverlap(box0.directions[2], box0, box1))
  12077. return false;
  12078. if (!axisOverlap(box1.directions[0], box0, box1))
  12079. return false;
  12080. if (!axisOverlap(box1.directions[1], box0, box1))
  12081. return false;
  12082. if (!axisOverlap(box1.directions[2], box0, box1))
  12083. return false;
  12084. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12085. return false;
  12086. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12087. return false;
  12088. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12089. return false;
  12090. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12091. return false;
  12092. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12093. return false;
  12094. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12095. return false;
  12096. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12097. return false;
  12098. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12099. return false;
  12100. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12101. return false;
  12102. return true;
  12103. };
  12104. return BoundingInfo;
  12105. }());
  12106. BABYLON.BoundingInfo = BoundingInfo;
  12107. })(BABYLON || (BABYLON = {}));
  12108. //# sourceMappingURL=babylon.boundingInfo.js.map
  12109. var BABYLON;
  12110. (function (BABYLON) {
  12111. var AbstractMesh = (function (_super) {
  12112. __extends(AbstractMesh, _super);
  12113. // Constructor
  12114. function AbstractMesh(name, scene) {
  12115. var _this = _super.call(this, name, scene) || this;
  12116. _this._facetNb = 0; // facet number
  12117. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12118. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12119. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12120. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12121. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12122. _this._subDiv = {
  12123. max: 1,
  12124. X: 1,
  12125. Y: 1,
  12126. Z: 1
  12127. };
  12128. // Events
  12129. /**
  12130. * An event triggered when this mesh collides with another one
  12131. * @type {BABYLON.Observable}
  12132. */
  12133. _this.onCollideObservable = new BABYLON.Observable();
  12134. /**
  12135. * An event triggered when the collision's position changes
  12136. * @type {BABYLON.Observable}
  12137. */
  12138. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12139. /**
  12140. * An event triggered after the world matrix is updated
  12141. * @type {BABYLON.Observable}
  12142. */
  12143. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12144. /**
  12145. * An event triggered when material is changed
  12146. * @type {BABYLON.Observable}
  12147. */
  12148. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12149. // Properties
  12150. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12151. _this.position = BABYLON.Vector3.Zero();
  12152. /**
  12153. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12154. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12155. * or
  12156. * 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.
  12157. * for more info check WebGl documentations
  12158. */
  12159. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12160. /**
  12161. * 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:
  12162. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12163. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12164. * 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.
  12165. */
  12166. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12167. /**
  12168. * 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.
  12169. * The default value is -1 which means don't break the query and wait till the result.
  12170. */
  12171. _this.occlusionRetryCount = -1;
  12172. _this._occlusionInternalRetryCounter = 0;
  12173. _this._isOccluded = false;
  12174. _this._isOcclusionQueryInProgress = false;
  12175. _this._rotation = BABYLON.Vector3.Zero();
  12176. _this._scaling = BABYLON.Vector3.One();
  12177. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12178. _this.visibility = 1.0;
  12179. _this.alphaIndex = Number.MAX_VALUE;
  12180. _this.infiniteDistance = false;
  12181. _this.isVisible = true;
  12182. _this.isPickable = true;
  12183. _this.showBoundingBox = false;
  12184. _this.showSubMeshesBoundingBox = false;
  12185. _this.isBlocker = false;
  12186. _this.enablePointerMoveEvents = false;
  12187. _this.renderingGroupId = 0;
  12188. _this._receiveShadows = false;
  12189. _this.renderOutline = false;
  12190. _this.outlineColor = BABYLON.Color3.Red();
  12191. _this.outlineWidth = 0.02;
  12192. _this.renderOverlay = false;
  12193. _this.overlayColor = BABYLON.Color3.Red();
  12194. _this.overlayAlpha = 0.5;
  12195. _this._hasVertexAlpha = false;
  12196. _this._useVertexColors = true;
  12197. _this._computeBonesUsingShaders = true;
  12198. _this._numBoneInfluencers = 4;
  12199. _this._applyFog = true;
  12200. _this.scalingDeterminant = 1;
  12201. _this.useOctreeForRenderingSelection = true;
  12202. _this.useOctreeForPicking = true;
  12203. _this.useOctreeForCollisions = true;
  12204. _this._layerMask = 0x0FFFFFFF;
  12205. /**
  12206. * True if the mesh must be rendered in any case.
  12207. */
  12208. _this.alwaysSelectAsActiveMesh = false;
  12209. // Collisions
  12210. _this._checkCollisions = false;
  12211. _this._collisionMask = -1;
  12212. _this._collisionGroup = -1;
  12213. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12214. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12215. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12216. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12217. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12218. // Edges
  12219. _this.edgesWidth = 1;
  12220. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12221. // Cache
  12222. _this._localWorld = BABYLON.Matrix.Zero();
  12223. _this._worldMatrix = BABYLON.Matrix.Zero();
  12224. _this._absolutePosition = BABYLON.Vector3.Zero();
  12225. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12226. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12227. _this._isDirty = false;
  12228. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12229. _this._isDisposed = false;
  12230. _this._renderId = 0;
  12231. _this._intersectionsInProgress = new Array();
  12232. _this._isWorldMatrixFrozen = false;
  12233. _this._unIndexed = false;
  12234. _this._lightSources = new Array();
  12235. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12236. if (collidedMesh === void 0) { collidedMesh = null; }
  12237. //TODO move this to the collision coordinator!
  12238. if (_this.getScene().workerCollisions)
  12239. newPosition.multiplyInPlace(_this._collider.radius);
  12240. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12241. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12242. _this.position.addInPlace(_this._diffPositionForCollisions);
  12243. }
  12244. if (collidedMesh) {
  12245. _this.onCollideObservable.notifyObservers(collidedMesh);
  12246. }
  12247. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12248. };
  12249. _this.getScene().addMesh(_this);
  12250. _this._resyncLightSources();
  12251. return _this;
  12252. }
  12253. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12254. get: function () {
  12255. return AbstractMesh._BILLBOARDMODE_NONE;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12261. get: function () {
  12262. return AbstractMesh._BILLBOARDMODE_X;
  12263. },
  12264. enumerable: true,
  12265. configurable: true
  12266. });
  12267. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12268. get: function () {
  12269. return AbstractMesh._BILLBOARDMODE_Y;
  12270. },
  12271. enumerable: true,
  12272. configurable: true
  12273. });
  12274. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12275. get: function () {
  12276. return AbstractMesh._BILLBOARDMODE_Z;
  12277. },
  12278. enumerable: true,
  12279. configurable: true
  12280. });
  12281. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12282. get: function () {
  12283. return AbstractMesh._BILLBOARDMODE_ALL;
  12284. },
  12285. enumerable: true,
  12286. configurable: true
  12287. });
  12288. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12289. /**
  12290. * Read-only : the number of facets in the mesh
  12291. */
  12292. get: function () {
  12293. return this._facetNb;
  12294. },
  12295. enumerable: true,
  12296. configurable: true
  12297. });
  12298. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12299. /**
  12300. * The number (integer) of subdivisions per axis in the partioning space
  12301. */
  12302. get: function () {
  12303. return this._partitioningSubdivisions;
  12304. },
  12305. set: function (nb) {
  12306. this._partitioningSubdivisions = nb;
  12307. },
  12308. enumerable: true,
  12309. configurable: true
  12310. });
  12311. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12312. /**
  12313. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12314. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12315. */
  12316. get: function () {
  12317. return this._partitioningBBoxRatio;
  12318. },
  12319. set: function (ratio) {
  12320. this._partitioningBBoxRatio = ratio;
  12321. },
  12322. enumerable: true,
  12323. configurable: true
  12324. });
  12325. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12326. /**
  12327. * Read-only boolean : is the feature facetData enabled ?
  12328. */
  12329. get: function () {
  12330. return this._facetDataEnabled;
  12331. },
  12332. enumerable: true,
  12333. configurable: true
  12334. });
  12335. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12336. set: function (callback) {
  12337. if (this._onCollideObserver) {
  12338. this.onCollideObservable.remove(this._onCollideObserver);
  12339. }
  12340. this._onCollideObserver = this.onCollideObservable.add(callback);
  12341. },
  12342. enumerable: true,
  12343. configurable: true
  12344. });
  12345. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12346. set: function (callback) {
  12347. if (this._onCollisionPositionChangeObserver) {
  12348. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12349. }
  12350. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12351. },
  12352. enumerable: true,
  12353. configurable: true
  12354. });
  12355. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12356. /**
  12357. * 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.
  12358. */
  12359. get: function () {
  12360. return this._isOccluded;
  12361. },
  12362. set: function (value) {
  12363. this._isOccluded = value;
  12364. },
  12365. enumerable: true,
  12366. configurable: true
  12367. });
  12368. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12369. /**
  12370. * Flag to check the progress status of the query
  12371. */
  12372. get: function () {
  12373. return this._isOcclusionQueryInProgress;
  12374. },
  12375. enumerable: true,
  12376. configurable: true
  12377. });
  12378. Object.defineProperty(AbstractMesh.prototype, "material", {
  12379. get: function () {
  12380. return this._material;
  12381. },
  12382. set: function (value) {
  12383. if (this._material === value) {
  12384. return;
  12385. }
  12386. this._material = value;
  12387. if (this.onMaterialChangedObservable.hasObservers) {
  12388. this.onMaterialChangedObservable.notifyObservers(this);
  12389. }
  12390. if (!this.subMeshes) {
  12391. return;
  12392. }
  12393. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12394. var subMesh = _a[_i];
  12395. subMesh.setEffect(null);
  12396. }
  12397. },
  12398. enumerable: true,
  12399. configurable: true
  12400. });
  12401. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12402. get: function () {
  12403. return this._receiveShadows;
  12404. },
  12405. set: function (value) {
  12406. if (this._receiveShadows === value) {
  12407. return;
  12408. }
  12409. this._receiveShadows = value;
  12410. this._markSubMeshesAsLightDirty();
  12411. },
  12412. enumerable: true,
  12413. configurable: true
  12414. });
  12415. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12416. get: function () {
  12417. return this._hasVertexAlpha;
  12418. },
  12419. set: function (value) {
  12420. if (this._hasVertexAlpha === value) {
  12421. return;
  12422. }
  12423. this._hasVertexAlpha = value;
  12424. this._markSubMeshesAsAttributesDirty();
  12425. },
  12426. enumerable: true,
  12427. configurable: true
  12428. });
  12429. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12430. get: function () {
  12431. return this._useVertexColors;
  12432. },
  12433. set: function (value) {
  12434. if (this._useVertexColors === value) {
  12435. return;
  12436. }
  12437. this._useVertexColors = value;
  12438. this._markSubMeshesAsAttributesDirty();
  12439. },
  12440. enumerable: true,
  12441. configurable: true
  12442. });
  12443. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12444. get: function () {
  12445. return this._computeBonesUsingShaders;
  12446. },
  12447. set: function (value) {
  12448. if (this._computeBonesUsingShaders === value) {
  12449. return;
  12450. }
  12451. this._computeBonesUsingShaders = value;
  12452. this._markSubMeshesAsAttributesDirty();
  12453. },
  12454. enumerable: true,
  12455. configurable: true
  12456. });
  12457. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12458. get: function () {
  12459. return this._numBoneInfluencers;
  12460. },
  12461. set: function (value) {
  12462. if (this._numBoneInfluencers === value) {
  12463. return;
  12464. }
  12465. this._numBoneInfluencers = value;
  12466. this._markSubMeshesAsAttributesDirty();
  12467. },
  12468. enumerable: true,
  12469. configurable: true
  12470. });
  12471. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12472. get: function () {
  12473. return this._applyFog;
  12474. },
  12475. set: function (value) {
  12476. if (this._applyFog === value) {
  12477. return;
  12478. }
  12479. this._applyFog = value;
  12480. this._markSubMeshesAsMiscDirty();
  12481. },
  12482. enumerable: true,
  12483. configurable: true
  12484. });
  12485. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12486. get: function () {
  12487. return this._layerMask;
  12488. },
  12489. set: function (value) {
  12490. if (value === this._layerMask) {
  12491. return;
  12492. }
  12493. this._layerMask = value;
  12494. this._resyncLightSources();
  12495. },
  12496. enumerable: true,
  12497. configurable: true
  12498. });
  12499. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12500. get: function () {
  12501. return this._collisionMask;
  12502. },
  12503. set: function (mask) {
  12504. this._collisionMask = !isNaN(mask) ? mask : -1;
  12505. },
  12506. enumerable: true,
  12507. configurable: true
  12508. });
  12509. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12510. get: function () {
  12511. return this._collisionGroup;
  12512. },
  12513. set: function (mask) {
  12514. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12515. },
  12516. enumerable: true,
  12517. configurable: true
  12518. });
  12519. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12520. get: function () {
  12521. return null;
  12522. },
  12523. enumerable: true,
  12524. configurable: true
  12525. });
  12526. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12527. get: function () {
  12528. return this._skeleton;
  12529. },
  12530. set: function (value) {
  12531. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12532. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12533. }
  12534. if (value && value.needInitialSkinMatrix) {
  12535. value._registerMeshWithPoseMatrix(this);
  12536. }
  12537. this._skeleton = value;
  12538. if (!this._skeleton) {
  12539. this._bonesTransformMatrices = null;
  12540. }
  12541. this._markSubMeshesAsAttributesDirty();
  12542. },
  12543. enumerable: true,
  12544. configurable: true
  12545. });
  12546. /**
  12547. * Boolean : true if the mesh has been disposed.
  12548. */
  12549. AbstractMesh.prototype.isDisposed = function () {
  12550. return this._isDisposed;
  12551. };
  12552. /**
  12553. * Returns the string "AbstractMesh"
  12554. */
  12555. AbstractMesh.prototype.getClassName = function () {
  12556. return "AbstractMesh";
  12557. };
  12558. /**
  12559. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12560. */
  12561. AbstractMesh.prototype.toString = function (fullDetails) {
  12562. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12563. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12564. if (this._skeleton) {
  12565. ret += ", skeleton: " + this._skeleton.name;
  12566. }
  12567. if (fullDetails) {
  12568. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12569. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12570. }
  12571. return ret;
  12572. };
  12573. AbstractMesh.prototype._rebuild = function () {
  12574. if (this._occlusionQuery) {
  12575. this._occlusionQuery = null;
  12576. }
  12577. if (this._edgesRenderer) {
  12578. this._edgesRenderer._rebuild();
  12579. }
  12580. if (!this.subMeshes) {
  12581. return;
  12582. }
  12583. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12584. var subMesh = _a[_i];
  12585. subMesh._rebuild();
  12586. }
  12587. };
  12588. AbstractMesh.prototype._resyncLightSources = function () {
  12589. this._lightSources.length = 0;
  12590. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12591. var light = _a[_i];
  12592. if (!light.isEnabled()) {
  12593. continue;
  12594. }
  12595. if (light.canAffectMesh(this)) {
  12596. this._lightSources.push(light);
  12597. }
  12598. }
  12599. this._markSubMeshesAsLightDirty();
  12600. };
  12601. AbstractMesh.prototype._resyncLighSource = function (light) {
  12602. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12603. var index = this._lightSources.indexOf(light);
  12604. if (index === -1) {
  12605. if (!isIn) {
  12606. return;
  12607. }
  12608. this._lightSources.push(light);
  12609. }
  12610. else {
  12611. if (isIn) {
  12612. return;
  12613. }
  12614. this._lightSources.splice(index, 1);
  12615. }
  12616. this._markSubMeshesAsLightDirty();
  12617. };
  12618. AbstractMesh.prototype._removeLightSource = function (light) {
  12619. var index = this._lightSources.indexOf(light);
  12620. if (index === -1) {
  12621. return;
  12622. }
  12623. this._lightSources.splice(index, 1);
  12624. };
  12625. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12626. if (!this.subMeshes) {
  12627. return;
  12628. }
  12629. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12630. var subMesh = _a[_i];
  12631. if (subMesh._materialDefines) {
  12632. func(subMesh._materialDefines);
  12633. }
  12634. }
  12635. };
  12636. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12637. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12638. };
  12639. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12640. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12641. };
  12642. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12643. if (!this.subMeshes) {
  12644. return;
  12645. }
  12646. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12647. var subMesh = _a[_i];
  12648. var material = subMesh.getMaterial();
  12649. if (material) {
  12650. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12651. }
  12652. }
  12653. };
  12654. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12655. /**
  12656. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12657. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12658. * Default : (0.0, 0.0, 0.0)
  12659. */
  12660. get: function () {
  12661. return this._rotation;
  12662. },
  12663. set: function (newRotation) {
  12664. this._rotation = newRotation;
  12665. },
  12666. enumerable: true,
  12667. configurable: true
  12668. });
  12669. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12670. /**
  12671. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12672. * Default : (1.0, 1.0, 1.0)
  12673. */
  12674. get: function () {
  12675. return this._scaling;
  12676. },
  12677. set: function (newScaling) {
  12678. this._scaling = newScaling;
  12679. if (this.physicsImpostor) {
  12680. this.physicsImpostor.forceUpdate();
  12681. }
  12682. },
  12683. enumerable: true,
  12684. configurable: true
  12685. });
  12686. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12687. /**
  12688. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12689. * It's null by default.
  12690. * 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)
  12691. */
  12692. get: function () {
  12693. return this._rotationQuaternion;
  12694. },
  12695. set: function (quaternion) {
  12696. this._rotationQuaternion = quaternion;
  12697. //reset the rotation vector.
  12698. if (quaternion && this.rotation.length()) {
  12699. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12700. }
  12701. },
  12702. enumerable: true,
  12703. configurable: true
  12704. });
  12705. // Methods
  12706. /**
  12707. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12708. * Returns the AbstractMesh.
  12709. */
  12710. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12711. this._poseMatrix.copyFrom(matrix);
  12712. return this;
  12713. };
  12714. /**
  12715. * Returns the mesh Pose matrix.
  12716. * Returned object : Matrix
  12717. */
  12718. AbstractMesh.prototype.getPoseMatrix = function () {
  12719. return this._poseMatrix;
  12720. };
  12721. /**
  12722. * Disables the mesh edger rendering mode.
  12723. * Returns the AbstractMesh.
  12724. */
  12725. AbstractMesh.prototype.disableEdgesRendering = function () {
  12726. if (this._edgesRenderer !== undefined) {
  12727. this._edgesRenderer.dispose();
  12728. this._edgesRenderer = undefined;
  12729. }
  12730. return this;
  12731. };
  12732. /**
  12733. * Enables the edge rendering mode on the mesh.
  12734. * This mode makes the mesh edges visible.
  12735. * Returns the AbstractMesh.
  12736. */
  12737. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12738. if (epsilon === void 0) { epsilon = 0.95; }
  12739. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12740. this.disableEdgesRendering();
  12741. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12742. return this;
  12743. };
  12744. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12745. /**
  12746. * Returns true if the mesh is blocked. Used by the class Mesh.
  12747. * Returns the boolean `false` by default.
  12748. */
  12749. get: function () {
  12750. return false;
  12751. },
  12752. enumerable: true,
  12753. configurable: true
  12754. });
  12755. /**
  12756. * Returns the mesh itself by default, used by the class Mesh.
  12757. * Returned type : AbstractMesh
  12758. */
  12759. AbstractMesh.prototype.getLOD = function (camera) {
  12760. return this;
  12761. };
  12762. /**
  12763. * Returns 0 by default, used by the class Mesh.
  12764. * Returns an integer.
  12765. */
  12766. AbstractMesh.prototype.getTotalVertices = function () {
  12767. return 0;
  12768. };
  12769. /**
  12770. * Returns null by default, used by the class Mesh.
  12771. * Returned type : integer array
  12772. */
  12773. AbstractMesh.prototype.getIndices = function () {
  12774. return null;
  12775. };
  12776. /**
  12777. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12778. * Returned type : float array or Float32Array
  12779. */
  12780. AbstractMesh.prototype.getVerticesData = function (kind) {
  12781. return null;
  12782. };
  12783. /**
  12784. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12785. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12786. * The `data` are either a numeric array either a Float32Array.
  12787. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12788. * 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).
  12789. * Note that a new underlying VertexBuffer object is created each call.
  12790. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12791. *
  12792. * Possible `kind` values :
  12793. * - BABYLON.VertexBuffer.PositionKind
  12794. * - BABYLON.VertexBuffer.UVKind
  12795. * - BABYLON.VertexBuffer.UV2Kind
  12796. * - BABYLON.VertexBuffer.UV3Kind
  12797. * - BABYLON.VertexBuffer.UV4Kind
  12798. * - BABYLON.VertexBuffer.UV5Kind
  12799. * - BABYLON.VertexBuffer.UV6Kind
  12800. * - BABYLON.VertexBuffer.ColorKind
  12801. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12802. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12803. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12804. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12805. *
  12806. * Returns the Mesh.
  12807. */
  12808. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12809. return null;
  12810. };
  12811. /**
  12812. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12813. * If the mesh has no geometry, it is simply returned as it is.
  12814. * The `data` are either a numeric array either a Float32Array.
  12815. * No new underlying VertexBuffer object is created.
  12816. * 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.
  12817. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12818. *
  12819. * Possible `kind` values :
  12820. * - BABYLON.VertexBuffer.PositionKind
  12821. * - BABYLON.VertexBuffer.UVKind
  12822. * - BABYLON.VertexBuffer.UV2Kind
  12823. * - BABYLON.VertexBuffer.UV3Kind
  12824. * - BABYLON.VertexBuffer.UV4Kind
  12825. * - BABYLON.VertexBuffer.UV5Kind
  12826. * - BABYLON.VertexBuffer.UV6Kind
  12827. * - BABYLON.VertexBuffer.ColorKind
  12828. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12829. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12830. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12831. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12832. *
  12833. * Returns the Mesh.
  12834. */
  12835. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12836. return null;
  12837. };
  12838. /**
  12839. * Sets the mesh indices.
  12840. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12841. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12842. * This method creates a new index buffer each call.
  12843. * Returns the Mesh.
  12844. */
  12845. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12846. return null;
  12847. };
  12848. /** Returns false by default, used by the class Mesh.
  12849. * Returns a boolean
  12850. */
  12851. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12852. return false;
  12853. };
  12854. /**
  12855. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12856. * Returns a BoundingInfo
  12857. */
  12858. AbstractMesh.prototype.getBoundingInfo = function () {
  12859. if (this._masterMesh) {
  12860. return this._masterMesh.getBoundingInfo();
  12861. }
  12862. if (!this._boundingInfo) {
  12863. this._updateBoundingInfo();
  12864. }
  12865. return this._boundingInfo;
  12866. };
  12867. /**
  12868. * Sets a mesh new object BoundingInfo.
  12869. * Returns the AbstractMesh.
  12870. */
  12871. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12872. this._boundingInfo = boundingInfo;
  12873. return this;
  12874. };
  12875. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12876. get: function () {
  12877. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12878. },
  12879. enumerable: true,
  12880. configurable: true
  12881. });
  12882. AbstractMesh.prototype._preActivate = function () {
  12883. };
  12884. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12885. };
  12886. AbstractMesh.prototype._activate = function (renderId) {
  12887. this._renderId = renderId;
  12888. };
  12889. /**
  12890. * Returns the last update of the World matrix
  12891. * Returns a Matrix.
  12892. */
  12893. AbstractMesh.prototype.getWorldMatrix = function () {
  12894. if (this._masterMesh) {
  12895. return this._masterMesh.getWorldMatrix();
  12896. }
  12897. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12898. this.computeWorldMatrix();
  12899. }
  12900. return this._worldMatrix;
  12901. };
  12902. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12903. /**
  12904. * Returns directly the last state of the mesh World matrix.
  12905. * A Matrix is returned.
  12906. */
  12907. get: function () {
  12908. return this._worldMatrix;
  12909. },
  12910. enumerable: true,
  12911. configurable: true
  12912. });
  12913. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12914. /**
  12915. * Returns the current mesh absolute position.
  12916. * Retuns a Vector3.
  12917. */
  12918. get: function () {
  12919. return this._absolutePosition;
  12920. },
  12921. enumerable: true,
  12922. configurable: true
  12923. });
  12924. /**
  12925. * Prevents the World matrix to be computed any longer.
  12926. * Returns the AbstractMesh.
  12927. */
  12928. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12929. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12930. this.computeWorldMatrix(true);
  12931. this._isWorldMatrixFrozen = true;
  12932. return this;
  12933. };
  12934. /**
  12935. * Allows back the World matrix computation.
  12936. * Returns the AbstractMesh.
  12937. */
  12938. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12939. this._isWorldMatrixFrozen = false;
  12940. this.computeWorldMatrix(true);
  12941. return this;
  12942. };
  12943. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12944. /**
  12945. * True if the World matrix has been frozen.
  12946. * Returns a boolean.
  12947. */
  12948. get: function () {
  12949. return this._isWorldMatrixFrozen;
  12950. },
  12951. enumerable: true,
  12952. configurable: true
  12953. });
  12954. /**
  12955. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12956. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12957. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12958. * The passed axis is also normalized.
  12959. * Returns the AbstractMesh.
  12960. */
  12961. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12962. axis.normalize();
  12963. if (!this.rotationQuaternion) {
  12964. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12965. this.rotation = BABYLON.Vector3.Zero();
  12966. }
  12967. var rotationQuaternion;
  12968. if (!space || space === BABYLON.Space.LOCAL) {
  12969. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12970. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12971. }
  12972. else {
  12973. if (this.parent) {
  12974. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12975. invertParentWorldMatrix.invert();
  12976. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12977. }
  12978. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12979. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12980. }
  12981. return this;
  12982. };
  12983. /**
  12984. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12985. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12986. * The passed axis is also normalized.
  12987. * Returns the AbstractMesh.
  12988. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12989. */
  12990. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12991. axis.normalize();
  12992. if (!this.rotationQuaternion) {
  12993. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12994. this.rotation.copyFromFloats(0, 0, 0);
  12995. }
  12996. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12997. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12998. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12999. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13000. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13001. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13002. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13003. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13004. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13005. return this;
  13006. };
  13007. /**
  13008. * Translates the mesh along the axis vector for the passed distance in the given space.
  13009. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13010. * Returns the AbstractMesh.
  13011. */
  13012. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13013. var displacementVector = axis.scale(distance);
  13014. if (!space || space === BABYLON.Space.LOCAL) {
  13015. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13016. this.setPositionWithLocalVector(tempV3);
  13017. }
  13018. else {
  13019. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13020. }
  13021. return this;
  13022. };
  13023. /**
  13024. * Adds a rotation step to the mesh current rotation.
  13025. * x, y, z are Euler angles expressed in radians.
  13026. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13027. * This means this rotation is made in the mesh local space only.
  13028. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13029. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13030. * ```javascript
  13031. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13032. * ```
  13033. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13034. * 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.
  13035. * Returns the AbstractMesh.
  13036. */
  13037. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13038. var rotationQuaternion;
  13039. if (this.rotationQuaternion) {
  13040. rotationQuaternion = this.rotationQuaternion;
  13041. }
  13042. else {
  13043. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13044. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13045. }
  13046. var accumulation = BABYLON.Tmp.Quaternion[0];
  13047. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13048. rotationQuaternion.multiplyInPlace(accumulation);
  13049. if (!this.rotationQuaternion) {
  13050. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13051. }
  13052. return this;
  13053. };
  13054. /**
  13055. * Retuns the mesh absolute position in the World.
  13056. * Returns a Vector3.
  13057. */
  13058. AbstractMesh.prototype.getAbsolutePosition = function () {
  13059. this.computeWorldMatrix();
  13060. return this._absolutePosition;
  13061. };
  13062. /**
  13063. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13064. * Returns the AbstractMesh.
  13065. */
  13066. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13067. if (!absolutePosition) {
  13068. return;
  13069. }
  13070. var absolutePositionX;
  13071. var absolutePositionY;
  13072. var absolutePositionZ;
  13073. if (absolutePosition.x === undefined) {
  13074. if (arguments.length < 3) {
  13075. return;
  13076. }
  13077. absolutePositionX = arguments[0];
  13078. absolutePositionY = arguments[1];
  13079. absolutePositionZ = arguments[2];
  13080. }
  13081. else {
  13082. absolutePositionX = absolutePosition.x;
  13083. absolutePositionY = absolutePosition.y;
  13084. absolutePositionZ = absolutePosition.z;
  13085. }
  13086. if (this.parent) {
  13087. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13088. invertParentWorldMatrix.invert();
  13089. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13090. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13091. }
  13092. else {
  13093. this.position.x = absolutePositionX;
  13094. this.position.y = absolutePositionY;
  13095. this.position.z = absolutePositionZ;
  13096. }
  13097. return this;
  13098. };
  13099. // ================================== Point of View Movement =================================
  13100. /**
  13101. * Perform relative position change from the point of view of behind the front of the mesh.
  13102. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13103. * Supports definition of mesh facing forward or backward.
  13104. * @param {number} amountRight
  13105. * @param {number} amountUp
  13106. * @param {number} amountForward
  13107. *
  13108. * Returns the AbstractMesh.
  13109. */
  13110. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13111. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13112. return this;
  13113. };
  13114. /**
  13115. * Calculate relative position change from the point of view of behind the front of the mesh.
  13116. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13117. * Supports definition of mesh facing forward or backward.
  13118. * @param {number} amountRight
  13119. * @param {number} amountUp
  13120. * @param {number} amountForward
  13121. *
  13122. * Returns a new Vector3.
  13123. */
  13124. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13125. var rotMatrix = new BABYLON.Matrix();
  13126. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13127. rotQuaternion.toRotationMatrix(rotMatrix);
  13128. var translationDelta = BABYLON.Vector3.Zero();
  13129. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13130. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13131. return translationDelta;
  13132. };
  13133. // ================================== Point of View Rotation =================================
  13134. /**
  13135. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13136. * Supports definition of mesh facing forward or backward.
  13137. * @param {number} flipBack
  13138. * @param {number} twirlClockwise
  13139. * @param {number} tiltRight
  13140. *
  13141. * Returns the AbstractMesh.
  13142. */
  13143. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13144. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13145. return this;
  13146. };
  13147. /**
  13148. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13149. * Supports definition of mesh facing forward or backward.
  13150. * @param {number} flipBack
  13151. * @param {number} twirlClockwise
  13152. * @param {number} tiltRight
  13153. *
  13154. * Returns a new Vector3.
  13155. */
  13156. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13157. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13158. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13159. };
  13160. /**
  13161. * Sets a new pivot matrix to the mesh.
  13162. * Returns the AbstractMesh.
  13163. */
  13164. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  13165. this._pivotMatrix = matrix;
  13166. this._cache.pivotMatrixUpdated = true;
  13167. return this;
  13168. };
  13169. /**
  13170. * Returns the mesh pivot matrix.
  13171. * Default : Identity.
  13172. * A Matrix is returned.
  13173. */
  13174. AbstractMesh.prototype.getPivotMatrix = function () {
  13175. return this._pivotMatrix;
  13176. };
  13177. AbstractMesh.prototype._isSynchronized = function () {
  13178. if (this._isDirty) {
  13179. return false;
  13180. }
  13181. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13182. return false;
  13183. if (this._cache.pivotMatrixUpdated) {
  13184. return false;
  13185. }
  13186. if (this.infiniteDistance) {
  13187. return false;
  13188. }
  13189. if (!this._cache.position.equals(this.position))
  13190. return false;
  13191. if (this.rotationQuaternion) {
  13192. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13193. return false;
  13194. }
  13195. if (!this._cache.rotation.equals(this.rotation))
  13196. return false;
  13197. if (!this._cache.scaling.equals(this.scaling))
  13198. return false;
  13199. return true;
  13200. };
  13201. AbstractMesh.prototype._initCache = function () {
  13202. _super.prototype._initCache.call(this);
  13203. this._cache.localMatrixUpdated = false;
  13204. this._cache.position = BABYLON.Vector3.Zero();
  13205. this._cache.scaling = BABYLON.Vector3.Zero();
  13206. this._cache.rotation = BABYLON.Vector3.Zero();
  13207. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13208. this._cache.billboardMode = -1;
  13209. };
  13210. AbstractMesh.prototype.markAsDirty = function (property) {
  13211. if (property === "rotation") {
  13212. this.rotationQuaternion = null;
  13213. }
  13214. this._currentRenderId = Number.MAX_VALUE;
  13215. this._isDirty = true;
  13216. return this;
  13217. };
  13218. /**
  13219. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13220. */
  13221. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13222. this.computeWorldMatrix();
  13223. var min = this.getBoundingInfo().boundingBox.minimumWorld;
  13224. var max = this.getBoundingInfo().boundingBox.maximumWorld;
  13225. var descendants = this.getDescendants(false, function (node) { return node.subMeshes; });
  13226. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13227. var descendant = descendants_1[_i];
  13228. var childMesh = descendant;
  13229. childMesh.computeWorldMatrix();
  13230. var minBox = childMesh.getBoundingInfo().boundingBox.minimumWorld;
  13231. var maxBox = childMesh.getBoundingInfo().boundingBox.maximumWorld;
  13232. BABYLON.Tools.CheckExtends(minBox, min, max);
  13233. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13234. }
  13235. return {
  13236. min: min,
  13237. max: max
  13238. };
  13239. };
  13240. /**
  13241. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13242. * Returns the AbstractMesh.
  13243. */
  13244. AbstractMesh.prototype._updateBoundingInfo = function () {
  13245. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13246. this._boundingInfo.update(this.worldMatrixFromCache);
  13247. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13248. return this;
  13249. };
  13250. /**
  13251. * Update a mesh's children BoundingInfo objects only.
  13252. * Returns the AbstractMesh.
  13253. */
  13254. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13255. if (!this.subMeshes) {
  13256. return;
  13257. }
  13258. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13259. var subMesh = this.subMeshes[subIndex];
  13260. if (!subMesh.IsGlobal) {
  13261. subMesh.updateBoundingInfo(matrix);
  13262. }
  13263. }
  13264. return this;
  13265. };
  13266. /**
  13267. * Computes the mesh World matrix and returns it.
  13268. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13269. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13270. * If the parameter `force`is set to `true`, the actual computation is done.
  13271. * Returns the mesh World Matrix.
  13272. */
  13273. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13274. if (this._isWorldMatrixFrozen) {
  13275. return this._worldMatrix;
  13276. }
  13277. if (!force && this.isSynchronized(true)) {
  13278. this._currentRenderId = this.getScene().getRenderId();
  13279. return this._worldMatrix;
  13280. }
  13281. this._cache.position.copyFrom(this.position);
  13282. this._cache.scaling.copyFrom(this.scaling);
  13283. this._cache.pivotMatrixUpdated = false;
  13284. this._cache.billboardMode = this.billboardMode;
  13285. this._currentRenderId = this.getScene().getRenderId();
  13286. this._isDirty = false;
  13287. // Scaling
  13288. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13289. // Rotation
  13290. //rotate, if quaternion is set and rotation was used
  13291. if (this.rotationQuaternion) {
  13292. var len = this.rotation.length();
  13293. if (len) {
  13294. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13295. this.rotation.copyFromFloats(0, 0, 0);
  13296. }
  13297. }
  13298. if (this.rotationQuaternion) {
  13299. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13300. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13301. }
  13302. else {
  13303. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13304. this._cache.rotation.copyFrom(this.rotation);
  13305. }
  13306. // Translation
  13307. if (this.infiniteDistance && !this.parent) {
  13308. var camera = this.getScene().activeCamera;
  13309. if (camera) {
  13310. var cameraWorldMatrix = camera.getWorldMatrix();
  13311. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13312. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13313. }
  13314. }
  13315. else {
  13316. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13317. }
  13318. // Composing transformations
  13319. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13320. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13321. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13322. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13323. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13324. // Need to decompose each rotation here
  13325. var currentPosition = BABYLON.Tmp.Vector3[3];
  13326. if (this.parent && this.parent.getWorldMatrix) {
  13327. if (this._meshToBoneReferal) {
  13328. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13329. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13330. }
  13331. else {
  13332. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13333. }
  13334. }
  13335. else {
  13336. currentPosition.copyFrom(this.position);
  13337. }
  13338. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13339. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13340. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13341. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13342. }
  13343. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13344. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13345. }
  13346. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13347. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13348. }
  13349. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13350. }
  13351. else {
  13352. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13353. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13354. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13355. }
  13356. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13357. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13358. }
  13359. // Local world
  13360. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13361. // Parent
  13362. if (this.parent && this.parent.getWorldMatrix) {
  13363. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13364. if (this._meshToBoneReferal) {
  13365. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13366. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13367. }
  13368. else {
  13369. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13370. }
  13371. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13372. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13373. this._worldMatrix.copyFrom(this._localWorld);
  13374. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13375. }
  13376. else {
  13377. if (this._meshToBoneReferal) {
  13378. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13379. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13380. }
  13381. else {
  13382. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13383. }
  13384. }
  13385. this._markSyncedWithParent();
  13386. }
  13387. else {
  13388. this._worldMatrix.copyFrom(this._localWorld);
  13389. }
  13390. // Bounding info
  13391. this._updateBoundingInfo();
  13392. // Absolute position
  13393. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13394. // Callbacks
  13395. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13396. if (!this._poseMatrix) {
  13397. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13398. }
  13399. return this._worldMatrix;
  13400. };
  13401. /**
  13402. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13403. * @param func: callback function to add
  13404. *
  13405. * Returns the AbstractMesh.
  13406. */
  13407. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13408. this.onAfterWorldMatrixUpdateObservable.add(func);
  13409. return this;
  13410. };
  13411. /**
  13412. * Removes a registered callback function.
  13413. * Returns the AbstractMesh.
  13414. */
  13415. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13416. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13417. return this;
  13418. };
  13419. /**
  13420. * Sets the mesh position in its local space.
  13421. * Returns the AbstractMesh.
  13422. */
  13423. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13424. this.computeWorldMatrix();
  13425. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13426. return this;
  13427. };
  13428. /**
  13429. * Returns the mesh position in the local space from the current World matrix values.
  13430. * Returns a new Vector3.
  13431. */
  13432. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13433. this.computeWorldMatrix();
  13434. var invLocalWorldMatrix = this._localWorld.clone();
  13435. invLocalWorldMatrix.invert();
  13436. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13437. };
  13438. /**
  13439. * Translates the mesh along the passed Vector3 in its local space.
  13440. * Returns the AbstractMesh.
  13441. */
  13442. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13443. this.computeWorldMatrix(true);
  13444. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13445. return this;
  13446. };
  13447. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13448. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13449. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13450. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13451. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13452. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13453. /// <returns>Mesh oriented towards targetMesh</returns>
  13454. if (yawCor === void 0) { yawCor = 0; }
  13455. if (pitchCor === void 0) { pitchCor = 0; }
  13456. if (rollCor === void 0) { rollCor = 0; }
  13457. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13458. var dv = AbstractMesh._lookAtVectorCache;
  13459. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13460. targetPoint.subtractToRef(pos, dv);
  13461. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13462. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13463. var pitch = Math.atan2(dv.y, len);
  13464. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13465. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13466. return this;
  13467. };
  13468. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13469. this._meshToBoneReferal = affectedMesh;
  13470. this.parent = bone;
  13471. if (bone.getWorldMatrix().determinant() < 0) {
  13472. this.scalingDeterminant *= -1;
  13473. }
  13474. return this;
  13475. };
  13476. AbstractMesh.prototype.detachFromBone = function () {
  13477. if (this.parent.getWorldMatrix().determinant() < 0) {
  13478. this.scalingDeterminant *= -1;
  13479. }
  13480. this._meshToBoneReferal = null;
  13481. this.parent = null;
  13482. return this;
  13483. };
  13484. /**
  13485. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13486. * A mesh is in the frustum if its bounding box intersects the frustum.
  13487. * Boolean returned.
  13488. */
  13489. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13490. return this._boundingInfo.isInFrustum(frustumPlanes);
  13491. };
  13492. /**
  13493. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13494. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13495. * Boolean returned.
  13496. */
  13497. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13498. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13499. ;
  13500. };
  13501. /**
  13502. * True if the mesh intersects another mesh or a SolidParticle object.
  13503. * 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)
  13504. * Returns a boolean.
  13505. */
  13506. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13507. if (!this._boundingInfo || !mesh._boundingInfo) {
  13508. return false;
  13509. }
  13510. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13511. };
  13512. /**
  13513. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13514. * Returns a boolean.
  13515. */
  13516. AbstractMesh.prototype.intersectsPoint = function (point) {
  13517. if (!this._boundingInfo) {
  13518. return false;
  13519. }
  13520. return this._boundingInfo.intersectsPoint(point);
  13521. };
  13522. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13523. return this.physicsImpostor;
  13524. };
  13525. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13526. if (!camera) {
  13527. camera = this.getScene().activeCamera;
  13528. }
  13529. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13530. };
  13531. /**
  13532. * Returns the distance from the mesh to the active camera.
  13533. * Returns a float.
  13534. */
  13535. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13536. if (!camera) {
  13537. camera = this.getScene().activeCamera;
  13538. }
  13539. return this.absolutePosition.subtract(camera.position).length();
  13540. };
  13541. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13542. if (!this.physicsImpostor) {
  13543. return;
  13544. }
  13545. this.physicsImpostor.applyImpulse(force, contactPoint);
  13546. return this;
  13547. };
  13548. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13549. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13550. return;
  13551. }
  13552. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13553. mainPivot: pivot1,
  13554. connectedPivot: pivot2,
  13555. nativeParams: options
  13556. });
  13557. return this;
  13558. };
  13559. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13560. // Collisions
  13561. /**
  13562. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13563. * Default `false`.
  13564. */
  13565. get: function () {
  13566. return this._checkCollisions;
  13567. },
  13568. set: function (collisionEnabled) {
  13569. this._checkCollisions = collisionEnabled;
  13570. if (this.getScene().workerCollisions) {
  13571. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13572. }
  13573. },
  13574. enumerable: true,
  13575. configurable: true
  13576. });
  13577. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13578. var globalPosition = this.getAbsolutePosition();
  13579. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13580. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13581. if (!this._collider) {
  13582. this._collider = new BABYLON.Collider();
  13583. }
  13584. this._collider.radius = this.ellipsoid;
  13585. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13586. return this;
  13587. };
  13588. // Submeshes octree
  13589. /**
  13590. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13591. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13592. * Returns an Octree of submeshes.
  13593. */
  13594. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13595. if (maxCapacity === void 0) { maxCapacity = 64; }
  13596. if (maxDepth === void 0) { maxDepth = 2; }
  13597. if (!this._submeshesOctree) {
  13598. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13599. }
  13600. this.computeWorldMatrix(true);
  13601. // Update octree
  13602. var bbox = this.getBoundingInfo().boundingBox;
  13603. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13604. return this._submeshesOctree;
  13605. };
  13606. // Collisions
  13607. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13608. this._generatePointsArray();
  13609. // Transformation
  13610. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13611. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13612. subMesh._lastColliderWorldVertices = [];
  13613. subMesh._trianglePlanes = [];
  13614. var start = subMesh.verticesStart;
  13615. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13616. for (var i = start; i < end; i++) {
  13617. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13618. }
  13619. }
  13620. // Collide
  13621. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13622. if (collider.collisionFound) {
  13623. collider.collidedMesh = this;
  13624. }
  13625. return this;
  13626. };
  13627. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13628. var subMeshes;
  13629. var len;
  13630. // Octrees
  13631. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13632. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13633. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13634. len = intersections.length;
  13635. subMeshes = intersections.data;
  13636. }
  13637. else {
  13638. subMeshes = this.subMeshes;
  13639. len = subMeshes.length;
  13640. }
  13641. for (var index = 0; index < len; index++) {
  13642. var subMesh = subMeshes[index];
  13643. // Bounding test
  13644. if (len > 1 && !subMesh._checkCollision(collider))
  13645. continue;
  13646. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13647. }
  13648. return this;
  13649. };
  13650. AbstractMesh.prototype._checkCollision = function (collider) {
  13651. // Bounding box test
  13652. if (!this._boundingInfo._checkCollision(collider))
  13653. return this;
  13654. // Transformation matrix
  13655. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13656. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13657. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13658. return this;
  13659. };
  13660. // Picking
  13661. AbstractMesh.prototype._generatePointsArray = function () {
  13662. return false;
  13663. };
  13664. /**
  13665. * Checks if the passed Ray intersects with the mesh.
  13666. * Returns an object PickingInfo.
  13667. */
  13668. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13669. var pickingInfo = new BABYLON.PickingInfo();
  13670. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13671. return pickingInfo;
  13672. }
  13673. if (!this._generatePointsArray()) {
  13674. return pickingInfo;
  13675. }
  13676. var intersectInfo = null;
  13677. // Octrees
  13678. var subMeshes;
  13679. var len;
  13680. if (this._submeshesOctree && this.useOctreeForPicking) {
  13681. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13682. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13683. len = intersections.length;
  13684. subMeshes = intersections.data;
  13685. }
  13686. else {
  13687. subMeshes = this.subMeshes;
  13688. len = subMeshes.length;
  13689. }
  13690. for (var index = 0; index < len; index++) {
  13691. var subMesh = subMeshes[index];
  13692. // Bounding test
  13693. if (len > 1 && !subMesh.canIntersects(ray))
  13694. continue;
  13695. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13696. if (currentIntersectInfo) {
  13697. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13698. intersectInfo = currentIntersectInfo;
  13699. intersectInfo.subMeshId = index;
  13700. if (fastCheck) {
  13701. break;
  13702. }
  13703. }
  13704. }
  13705. }
  13706. if (intersectInfo) {
  13707. // Get picked point
  13708. var world = this.getWorldMatrix();
  13709. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13710. var direction = ray.direction.clone();
  13711. direction = direction.scale(intersectInfo.distance);
  13712. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13713. var pickedPoint = worldOrigin.add(worldDirection);
  13714. // Return result
  13715. pickingInfo.hit = true;
  13716. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13717. pickingInfo.pickedPoint = pickedPoint;
  13718. pickingInfo.pickedMesh = this;
  13719. pickingInfo.bu = intersectInfo.bu;
  13720. pickingInfo.bv = intersectInfo.bv;
  13721. pickingInfo.faceId = intersectInfo.faceId;
  13722. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13723. return pickingInfo;
  13724. }
  13725. return pickingInfo;
  13726. };
  13727. /**
  13728. * Clones the mesh, used by the class Mesh.
  13729. * Just returns `null` for an AbstractMesh.
  13730. */
  13731. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13732. return null;
  13733. };
  13734. /**
  13735. * Disposes all the mesh submeshes.
  13736. * Returns the AbstractMesh.
  13737. */
  13738. AbstractMesh.prototype.releaseSubMeshes = function () {
  13739. if (this.subMeshes) {
  13740. while (this.subMeshes.length) {
  13741. this.subMeshes[0].dispose();
  13742. }
  13743. }
  13744. else {
  13745. this.subMeshes = new Array();
  13746. }
  13747. return this;
  13748. };
  13749. /**
  13750. * Disposes the AbstractMesh.
  13751. * Some internal references are kept for further use.
  13752. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13753. * Returns nothing.
  13754. */
  13755. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13756. var _this = this;
  13757. var index;
  13758. // Action manager
  13759. if (this.actionManager) {
  13760. this.actionManager.dispose();
  13761. this.actionManager = null;
  13762. }
  13763. // Skeleton
  13764. this.skeleton = null;
  13765. // Animations
  13766. this.getScene().stopAnimation(this);
  13767. // Physics
  13768. if (this.physicsImpostor) {
  13769. this.physicsImpostor.dispose();
  13770. }
  13771. // Intersections in progress
  13772. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13773. var other = this._intersectionsInProgress[index];
  13774. var pos = other._intersectionsInProgress.indexOf(this);
  13775. other._intersectionsInProgress.splice(pos, 1);
  13776. }
  13777. this._intersectionsInProgress = [];
  13778. // Lights
  13779. var lights = this.getScene().lights;
  13780. lights.forEach(function (light) {
  13781. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13782. if (meshIndex !== -1) {
  13783. light.includedOnlyMeshes.splice(meshIndex, 1);
  13784. }
  13785. meshIndex = light.excludedMeshes.indexOf(_this);
  13786. if (meshIndex !== -1) {
  13787. light.excludedMeshes.splice(meshIndex, 1);
  13788. }
  13789. // Shadow generators
  13790. var generator = light.getShadowGenerator();
  13791. if (generator) {
  13792. var shadowMap = generator.getShadowMap();
  13793. meshIndex = shadowMap.renderList.indexOf(_this);
  13794. if (meshIndex !== -1) {
  13795. shadowMap.renderList.splice(meshIndex, 1);
  13796. }
  13797. }
  13798. });
  13799. // Edges
  13800. if (this._edgesRenderer) {
  13801. this._edgesRenderer.dispose();
  13802. this._edgesRenderer = null;
  13803. }
  13804. // SubMeshes
  13805. if (this.getClassName() !== "InstancedMesh") {
  13806. this.releaseSubMeshes();
  13807. }
  13808. // Octree
  13809. var sceneOctree = this.getScene().selectionOctree;
  13810. if (sceneOctree) {
  13811. var index = sceneOctree.dynamicContent.indexOf(this);
  13812. if (index !== -1) {
  13813. sceneOctree.dynamicContent.splice(index, 1);
  13814. }
  13815. }
  13816. // Query
  13817. var engine = this.getScene().getEngine();
  13818. if (this._occlusionQuery) {
  13819. this._isOcclusionQueryInProgress = false;
  13820. engine.deleteQuery(this._occlusionQuery);
  13821. this._occlusionQuery = null;
  13822. }
  13823. // Engine
  13824. engine.wipeCaches();
  13825. // Remove from scene
  13826. this.getScene().removeMesh(this);
  13827. if (!doNotRecurse) {
  13828. // Particles
  13829. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13830. if (this.getScene().particleSystems[index].emitter === this) {
  13831. this.getScene().particleSystems[index].dispose();
  13832. index--;
  13833. }
  13834. }
  13835. // Children
  13836. var objects = this.getDescendants(true);
  13837. for (index = 0; index < objects.length; index++) {
  13838. objects[index].dispose();
  13839. }
  13840. }
  13841. else {
  13842. var childMeshes = this.getChildMeshes(true);
  13843. for (index = 0; index < childMeshes.length; index++) {
  13844. var child = childMeshes[index];
  13845. child.parent = null;
  13846. child.computeWorldMatrix(true);
  13847. }
  13848. }
  13849. // facet data
  13850. if (this._facetDataEnabled) {
  13851. this.disableFacetData();
  13852. }
  13853. this.onAfterWorldMatrixUpdateObservable.clear();
  13854. this.onCollideObservable.clear();
  13855. this.onCollisionPositionChangeObservable.clear();
  13856. this._isDisposed = true;
  13857. _super.prototype.dispose.call(this);
  13858. };
  13859. /**
  13860. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13861. * This Vector3 is expressed in the World space.
  13862. */
  13863. AbstractMesh.prototype.getDirection = function (localAxis) {
  13864. var result = BABYLON.Vector3.Zero();
  13865. this.getDirectionToRef(localAxis, result);
  13866. return result;
  13867. };
  13868. /**
  13869. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13870. * localAxis is expressed in the mesh local space.
  13871. * result is computed in the Wordl space from the mesh World matrix.
  13872. * Returns the AbstractMesh.
  13873. */
  13874. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13875. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13876. return this;
  13877. };
  13878. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13880. if (this.getScene().getRenderId() == 0) {
  13881. this.computeWorldMatrix(true);
  13882. }
  13883. var wm = this.getWorldMatrix();
  13884. if (space == BABYLON.Space.WORLD) {
  13885. var tmat = BABYLON.Tmp.Matrix[0];
  13886. wm.invertToRef(tmat);
  13887. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13888. }
  13889. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13890. this._pivotMatrix.m[12] = -point.x;
  13891. this._pivotMatrix.m[13] = -point.y;
  13892. this._pivotMatrix.m[14] = -point.z;
  13893. this._cache.pivotMatrixUpdated = true;
  13894. return this;
  13895. };
  13896. /**
  13897. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13898. */
  13899. AbstractMesh.prototype.getPivotPoint = function () {
  13900. var point = BABYLON.Vector3.Zero();
  13901. this.getPivotPointToRef(point);
  13902. return point;
  13903. };
  13904. /**
  13905. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13906. * Returns the AbstractMesh.
  13907. */
  13908. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13909. result.x = -this._pivotMatrix.m[12];
  13910. result.y = -this._pivotMatrix.m[13];
  13911. result.z = -this._pivotMatrix.m[14];
  13912. return this;
  13913. };
  13914. /**
  13915. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13916. */
  13917. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13918. var point = BABYLON.Vector3.Zero();
  13919. this.getAbsolutePivotPointToRef(point);
  13920. return point;
  13921. };
  13922. /**
  13923. * Defines the passed mesh as the parent of the current mesh.
  13924. * Returns the AbstractMesh.
  13925. */
  13926. AbstractMesh.prototype.setParent = function (mesh) {
  13927. var child = this;
  13928. var parent = mesh;
  13929. if (mesh == null) {
  13930. var rotation = BABYLON.Tmp.Quaternion[0];
  13931. var position = BABYLON.Tmp.Vector3[0];
  13932. var scale = BABYLON.Tmp.Vector3[1];
  13933. child.getWorldMatrix().decompose(scale, rotation, position);
  13934. if (child.rotationQuaternion) {
  13935. child.rotationQuaternion.copyFrom(rotation);
  13936. }
  13937. else {
  13938. rotation.toEulerAnglesToRef(child.rotation);
  13939. }
  13940. child.position.x = position.x;
  13941. child.position.y = position.y;
  13942. child.position.z = position.z;
  13943. }
  13944. else {
  13945. var position = BABYLON.Tmp.Vector3[0];
  13946. var m1 = BABYLON.Tmp.Matrix[0];
  13947. parent.getWorldMatrix().invertToRef(m1);
  13948. BABYLON.Vector3.TransformCoordinatesToRef(child.position, m1, position);
  13949. child.position.copyFrom(position);
  13950. }
  13951. child.parent = parent;
  13952. return this;
  13953. };
  13954. /**
  13955. * Adds the passed mesh as a child to the current mesh.
  13956. * Returns the AbstractMesh.
  13957. */
  13958. AbstractMesh.prototype.addChild = function (mesh) {
  13959. mesh.setParent(this);
  13960. return this;
  13961. };
  13962. /**
  13963. * Removes the passed mesh from the current mesh children list.
  13964. * Returns the AbstractMesh.
  13965. */
  13966. AbstractMesh.prototype.removeChild = function (mesh) {
  13967. mesh.setParent(null);
  13968. return this;
  13969. };
  13970. /**
  13971. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13972. * Returns the AbstractMesh.
  13973. */
  13974. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13975. result.x = this._pivotMatrix.m[12];
  13976. result.y = this._pivotMatrix.m[13];
  13977. result.z = this._pivotMatrix.m[14];
  13978. this.getPivotPointToRef(result);
  13979. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13980. return this;
  13981. };
  13982. // Facet data
  13983. /**
  13984. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13985. * Returns the AbstractMesh.
  13986. */
  13987. AbstractMesh.prototype._initFacetData = function () {
  13988. if (!this._facetNormals) {
  13989. this._facetNormals = new Array();
  13990. }
  13991. if (!this._facetPositions) {
  13992. this._facetPositions = new Array();
  13993. }
  13994. if (!this._facetPartitioning) {
  13995. this._facetPartitioning = new Array();
  13996. }
  13997. this._facetNb = this.getIndices().length / 3;
  13998. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13999. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14000. for (var f = 0; f < this._facetNb; f++) {
  14001. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14002. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14003. }
  14004. this._facetDataEnabled = true;
  14005. return this;
  14006. };
  14007. /**
  14008. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14009. * This method can be called within the render loop.
  14010. * 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.
  14011. * Returns the AbstractMesh.
  14012. */
  14013. AbstractMesh.prototype.updateFacetData = function () {
  14014. if (!this._facetDataEnabled) {
  14015. this._initFacetData();
  14016. }
  14017. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14018. var indices = this.getIndices();
  14019. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14020. var bInfo = this.getBoundingInfo();
  14021. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14022. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14023. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14024. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14025. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14026. this._subDiv.max = this._partitioningSubdivisions;
  14027. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14028. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14029. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14030. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14031. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14032. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14033. // set the parameters for ComputeNormals()
  14034. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14035. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14036. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14037. this._facetParameters.bInfo = bInfo;
  14038. this._facetParameters.bbSize = this._bbSize;
  14039. this._facetParameters.subDiv = this._subDiv;
  14040. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14041. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14042. return this;
  14043. };
  14044. /**
  14045. * Returns the facetLocalNormals array.
  14046. * The normals are expressed in the mesh local space.
  14047. */
  14048. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14049. if (!this._facetNormals) {
  14050. this.updateFacetData();
  14051. }
  14052. return this._facetNormals;
  14053. };
  14054. /**
  14055. * Returns the facetLocalPositions array.
  14056. * The facet positions are expressed in the mesh local space.
  14057. */
  14058. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14059. if (!this._facetPositions) {
  14060. this.updateFacetData();
  14061. }
  14062. return this._facetPositions;
  14063. };
  14064. /**
  14065. * Returns the facetLocalPartioning array.
  14066. */
  14067. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14068. if (!this._facetPartitioning) {
  14069. this.updateFacetData();
  14070. }
  14071. return this._facetPartitioning;
  14072. };
  14073. /**
  14074. * Returns the i-th facet position in the world system.
  14075. * This method allocates a new Vector3 per call.
  14076. */
  14077. AbstractMesh.prototype.getFacetPosition = function (i) {
  14078. var pos = BABYLON.Vector3.Zero();
  14079. this.getFacetPositionToRef(i, pos);
  14080. return pos;
  14081. };
  14082. /**
  14083. * Sets the reference Vector3 with the i-th facet position in the world system.
  14084. * Returns the AbstractMesh.
  14085. */
  14086. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14087. var localPos = (this.getFacetLocalPositions())[i];
  14088. var world = this.getWorldMatrix();
  14089. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14090. return this;
  14091. };
  14092. /**
  14093. * Returns the i-th facet normal in the world system.
  14094. * This method allocates a new Vector3 per call.
  14095. */
  14096. AbstractMesh.prototype.getFacetNormal = function (i) {
  14097. var norm = BABYLON.Vector3.Zero();
  14098. this.getFacetNormalToRef(i, norm);
  14099. return norm;
  14100. };
  14101. /**
  14102. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14103. * Returns the AbstractMesh.
  14104. */
  14105. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14106. var localNorm = (this.getFacetLocalNormals())[i];
  14107. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14108. return this;
  14109. };
  14110. /**
  14111. * 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).
  14112. */
  14113. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14114. var bInfo = this.getBoundingInfo();
  14115. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14116. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14117. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14118. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14119. return null;
  14120. }
  14121. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14122. };
  14123. /**
  14124. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14125. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14126. * 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.
  14127. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14128. * 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.
  14129. */
  14130. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14131. if (checkFace === void 0) { checkFace = false; }
  14132. if (facing === void 0) { facing = true; }
  14133. var world = this.getWorldMatrix();
  14134. var invMat = BABYLON.Tmp.Matrix[5];
  14135. world.invertToRef(invMat);
  14136. var invVect = BABYLON.Tmp.Vector3[8];
  14137. var closest = null;
  14138. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14139. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14140. if (projected) {
  14141. // tranform the local computed projected vector to world coordinates
  14142. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14143. }
  14144. return closest;
  14145. };
  14146. /**
  14147. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14148. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14149. * 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.
  14150. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14151. * 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.
  14152. */
  14153. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14154. if (checkFace === void 0) { checkFace = false; }
  14155. if (facing === void 0) { facing = true; }
  14156. var closest = null;
  14157. var tmpx = 0.0;
  14158. var tmpy = 0.0;
  14159. var tmpz = 0.0;
  14160. var d = 0.0; // tmp dot facet normal * facet position
  14161. var t0 = 0.0;
  14162. var projx = 0.0;
  14163. var projy = 0.0;
  14164. var projz = 0.0;
  14165. // Get all the facets in the same partitioning block than (x, y, z)
  14166. var facetPositions = this.getFacetLocalPositions();
  14167. var facetNormals = this.getFacetLocalNormals();
  14168. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14169. if (!facetsInBlock) {
  14170. return null;
  14171. }
  14172. // Get the closest facet to (x, y, z)
  14173. var shortest = Number.MAX_VALUE; // init distance vars
  14174. var tmpDistance = shortest;
  14175. var fib; // current facet in the block
  14176. var norm; // current facet normal
  14177. var p0; // current facet barycenter position
  14178. // loop on all the facets in the current partitioning block
  14179. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14180. fib = facetsInBlock[idx];
  14181. norm = facetNormals[fib];
  14182. p0 = facetPositions[fib];
  14183. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14184. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14185. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14186. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14187. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14188. projx = x + norm.x * t0;
  14189. projy = y + norm.y * t0;
  14190. projz = z + norm.z * t0;
  14191. tmpx = projx - x;
  14192. tmpy = projy - y;
  14193. tmpz = projz - z;
  14194. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14195. if (tmpDistance < shortest) {
  14196. shortest = tmpDistance;
  14197. closest = fib;
  14198. if (projected) {
  14199. projected.x = projx;
  14200. projected.y = projy;
  14201. projected.z = projz;
  14202. }
  14203. }
  14204. }
  14205. }
  14206. return closest;
  14207. };
  14208. /**
  14209. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14210. */
  14211. AbstractMesh.prototype.getFacetDataParameters = function () {
  14212. return this._facetParameters;
  14213. };
  14214. /**
  14215. * Disables the feature FacetData and frees the related memory.
  14216. * Returns the AbstractMesh.
  14217. */
  14218. AbstractMesh.prototype.disableFacetData = function () {
  14219. if (this._facetDataEnabled) {
  14220. this._facetDataEnabled = false;
  14221. this._facetPositions = null;
  14222. this._facetNormals = null;
  14223. this._facetPartitioning = null;
  14224. this._facetParameters = null;
  14225. }
  14226. return this;
  14227. };
  14228. /**
  14229. * Creates new normals data for the mesh.
  14230. * @param updatable.
  14231. */
  14232. AbstractMesh.prototype.createNormals = function (updatable) {
  14233. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14234. var indices = this.getIndices();
  14235. var normals;
  14236. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14237. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14238. }
  14239. else {
  14240. normals = [];
  14241. }
  14242. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14243. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14244. };
  14245. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14246. var engine = this.getEngine();
  14247. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14248. this._isOccluded = false;
  14249. return;
  14250. }
  14251. if (this.isOcclusionQueryInProgress) {
  14252. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14253. if (isOcclusionQueryAvailable) {
  14254. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14255. this._isOcclusionQueryInProgress = false;
  14256. this._occlusionInternalRetryCounter = 0;
  14257. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14258. }
  14259. else {
  14260. this._occlusionInternalRetryCounter++;
  14261. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14262. this._isOcclusionQueryInProgress = false;
  14263. this._occlusionInternalRetryCounter = 0;
  14264. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14265. // if strict continue the last state of the object.
  14266. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14267. }
  14268. else {
  14269. return;
  14270. }
  14271. }
  14272. }
  14273. var scene = this.getScene();
  14274. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14275. if (!this._occlusionQuery) {
  14276. this._occlusionQuery = engine.createQuery();
  14277. }
  14278. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14279. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14280. engine.endQuery(this.occlusionQueryAlgorithmType);
  14281. this._isOcclusionQueryInProgress = true;
  14282. };
  14283. // Statics
  14284. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14285. AbstractMesh._BILLBOARDMODE_X = 1;
  14286. AbstractMesh._BILLBOARDMODE_Y = 2;
  14287. AbstractMesh._BILLBOARDMODE_Z = 4;
  14288. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14289. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14290. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14291. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14292. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14293. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14294. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14295. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14296. return AbstractMesh;
  14297. }(BABYLON.Node));
  14298. BABYLON.AbstractMesh = AbstractMesh;
  14299. })(BABYLON || (BABYLON = {}));
  14300. //# sourceMappingURL=babylon.abstractMesh.js.map
  14301. var BABYLON;
  14302. (function (BABYLON) {
  14303. var Light = (function (_super) {
  14304. __extends(Light, _super);
  14305. /**
  14306. * Creates a Light object in the scene.
  14307. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14308. */
  14309. function Light(name, scene) {
  14310. var _this = _super.call(this, name, scene) || this;
  14311. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14312. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14313. _this.intensity = 1.0;
  14314. _this.range = Number.MAX_VALUE;
  14315. /**
  14316. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14317. * of light.
  14318. */
  14319. _this._photometricScale = 1.0;
  14320. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14321. _this._radius = 0.00001;
  14322. _this.renderPriority = 0;
  14323. /**
  14324. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14325. * the current shadow generator.
  14326. */
  14327. _this.shadowEnabled = true;
  14328. _this._excludeWithLayerMask = 0;
  14329. _this._includeOnlyWithLayerMask = 0;
  14330. _this._lightmapMode = 0;
  14331. _this._excludedMeshesIds = new Array();
  14332. _this._includedOnlyMeshesIds = new Array();
  14333. _this.getScene().addLight(_this);
  14334. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14335. _this._buildUniformLayout();
  14336. _this.includedOnlyMeshes = new Array();
  14337. _this.excludedMeshes = new Array();
  14338. _this._resyncMeshes();
  14339. return _this;
  14340. }
  14341. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14342. /**
  14343. * If every light affecting the material is in this lightmapMode,
  14344. * material.lightmapTexture adds or multiplies
  14345. * (depends on material.useLightmapAsShadowmap)
  14346. * after every other light calculations.
  14347. */
  14348. get: function () {
  14349. return Light._LIGHTMAP_DEFAULT;
  14350. },
  14351. enumerable: true,
  14352. configurable: true
  14353. });
  14354. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14355. /**
  14356. * material.lightmapTexture as only diffuse lighting from this light
  14357. * adds pnly specular lighting from this light
  14358. * adds dynamic shadows
  14359. */
  14360. get: function () {
  14361. return Light._LIGHTMAP_SPECULAR;
  14362. },
  14363. enumerable: true,
  14364. configurable: true
  14365. });
  14366. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14367. /**
  14368. * material.lightmapTexture as only lighting
  14369. * no light calculation from this light
  14370. * only adds dynamic shadows from this light
  14371. */
  14372. get: function () {
  14373. return Light._LIGHTMAP_SHADOWSONLY;
  14374. },
  14375. enumerable: true,
  14376. configurable: true
  14377. });
  14378. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14379. /**
  14380. * Each light type uses the default quantity according to its type:
  14381. * point/spot lights use luminous intensity
  14382. * directional lights use illuminance
  14383. */
  14384. get: function () {
  14385. return Light._INTENSITYMODE_AUTOMATIC;
  14386. },
  14387. enumerable: true,
  14388. configurable: true
  14389. });
  14390. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14391. /**
  14392. * lumen (lm)
  14393. */
  14394. get: function () {
  14395. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14396. },
  14397. enumerable: true,
  14398. configurable: true
  14399. });
  14400. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14401. /**
  14402. * candela (lm/sr)
  14403. */
  14404. get: function () {
  14405. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14406. },
  14407. enumerable: true,
  14408. configurable: true
  14409. });
  14410. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14411. /**
  14412. * lux (lm/m^2)
  14413. */
  14414. get: function () {
  14415. return Light._INTENSITYMODE_ILLUMINANCE;
  14416. },
  14417. enumerable: true,
  14418. configurable: true
  14419. });
  14420. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14421. /**
  14422. * nit (cd/m^2)
  14423. */
  14424. get: function () {
  14425. return Light._INTENSITYMODE_LUMINANCE;
  14426. },
  14427. enumerable: true,
  14428. configurable: true
  14429. });
  14430. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14431. /**
  14432. * Light type const id of the point light.
  14433. */
  14434. get: function () {
  14435. return Light._LIGHTTYPEID_POINTLIGHT;
  14436. },
  14437. enumerable: true,
  14438. configurable: true
  14439. });
  14440. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14441. /**
  14442. * Light type const id of the directional light.
  14443. */
  14444. get: function () {
  14445. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14446. },
  14447. enumerable: true,
  14448. configurable: true
  14449. });
  14450. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14451. /**
  14452. * Light type const id of the spot light.
  14453. */
  14454. get: function () {
  14455. return Light._LIGHTTYPEID_SPOTLIGHT;
  14456. },
  14457. enumerable: true,
  14458. configurable: true
  14459. });
  14460. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14461. /**
  14462. * Light type const id of the hemispheric light.
  14463. */
  14464. get: function () {
  14465. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14466. },
  14467. enumerable: true,
  14468. configurable: true
  14469. });
  14470. Object.defineProperty(Light.prototype, "intensityMode", {
  14471. /**
  14472. * Gets the photometric scale used to interpret the intensity.
  14473. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14474. */
  14475. get: function () {
  14476. return this._intensityMode;
  14477. },
  14478. /**
  14479. * Sets the photometric scale used to interpret the intensity.
  14480. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14481. */
  14482. set: function (value) {
  14483. this._intensityMode = value;
  14484. this._computePhotometricScale();
  14485. },
  14486. enumerable: true,
  14487. configurable: true
  14488. });
  14489. ;
  14490. ;
  14491. Object.defineProperty(Light.prototype, "radius", {
  14492. /**
  14493. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14494. */
  14495. get: function () {
  14496. return this._radius;
  14497. },
  14498. /**
  14499. * sets the light radius used by PBR Materials to simulate soft area lights.
  14500. */
  14501. set: function (value) {
  14502. this._radius = value;
  14503. this._computePhotometricScale();
  14504. },
  14505. enumerable: true,
  14506. configurable: true
  14507. });
  14508. ;
  14509. ;
  14510. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14511. get: function () {
  14512. return this._includedOnlyMeshes;
  14513. },
  14514. set: function (value) {
  14515. this._includedOnlyMeshes = value;
  14516. this._hookArrayForIncludedOnly(value);
  14517. },
  14518. enumerable: true,
  14519. configurable: true
  14520. });
  14521. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14522. get: function () {
  14523. return this._excludedMeshes;
  14524. },
  14525. set: function (value) {
  14526. this._excludedMeshes = value;
  14527. this._hookArrayForExcluded(value);
  14528. },
  14529. enumerable: true,
  14530. configurable: true
  14531. });
  14532. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14533. get: function () {
  14534. return this._excludeWithLayerMask;
  14535. },
  14536. set: function (value) {
  14537. this._excludeWithLayerMask = value;
  14538. this._resyncMeshes();
  14539. },
  14540. enumerable: true,
  14541. configurable: true
  14542. });
  14543. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14544. get: function () {
  14545. return this._includeOnlyWithLayerMask;
  14546. },
  14547. set: function (value) {
  14548. this._includeOnlyWithLayerMask = value;
  14549. this._resyncMeshes();
  14550. },
  14551. enumerable: true,
  14552. configurable: true
  14553. });
  14554. Object.defineProperty(Light.prototype, "lightmapMode", {
  14555. get: function () {
  14556. return this._lightmapMode;
  14557. },
  14558. set: function (value) {
  14559. if (this._lightmapMode === value) {
  14560. return;
  14561. }
  14562. this._lightmapMode = value;
  14563. this._markMeshesAsLightDirty();
  14564. },
  14565. enumerable: true,
  14566. configurable: true
  14567. });
  14568. Light.prototype._buildUniformLayout = function () {
  14569. // Overridden
  14570. };
  14571. /**
  14572. * Returns the string "Light".
  14573. */
  14574. Light.prototype.getClassName = function () {
  14575. return "Light";
  14576. };
  14577. /**
  14578. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14579. */
  14580. Light.prototype.toString = function (fullDetails) {
  14581. var ret = "Name: " + this.name;
  14582. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14583. if (this.animations) {
  14584. for (var i = 0; i < this.animations.length; i++) {
  14585. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14586. }
  14587. }
  14588. if (fullDetails) {
  14589. }
  14590. return ret;
  14591. };
  14592. /**
  14593. * Set the enabled state of this node.
  14594. * @param {boolean} value - the new enabled state
  14595. * @see isEnabled
  14596. */
  14597. Light.prototype.setEnabled = function (value) {
  14598. _super.prototype.setEnabled.call(this, value);
  14599. this._resyncMeshes();
  14600. };
  14601. /**
  14602. * Returns the Light associated shadow generator.
  14603. */
  14604. Light.prototype.getShadowGenerator = function () {
  14605. return this._shadowGenerator;
  14606. };
  14607. /**
  14608. * Returns a Vector3, the absolute light position in the World.
  14609. */
  14610. Light.prototype.getAbsolutePosition = function () {
  14611. return BABYLON.Vector3.Zero();
  14612. };
  14613. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14614. };
  14615. Light.prototype._getWorldMatrix = function () {
  14616. return BABYLON.Matrix.Identity();
  14617. };
  14618. /**
  14619. * Boolean : True if the light will affect the passed mesh.
  14620. */
  14621. Light.prototype.canAffectMesh = function (mesh) {
  14622. if (!mesh) {
  14623. return true;
  14624. }
  14625. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14626. return false;
  14627. }
  14628. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14629. return false;
  14630. }
  14631. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14632. return false;
  14633. }
  14634. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14635. return false;
  14636. }
  14637. return true;
  14638. };
  14639. /**
  14640. * Returns the light World matrix.
  14641. */
  14642. Light.prototype.getWorldMatrix = function () {
  14643. this._currentRenderId = this.getScene().getRenderId();
  14644. var worldMatrix = this._getWorldMatrix();
  14645. if (this.parent && this.parent.getWorldMatrix) {
  14646. if (!this._parentedWorldMatrix) {
  14647. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14648. }
  14649. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14650. this._markSyncedWithParent();
  14651. return this._parentedWorldMatrix;
  14652. }
  14653. return worldMatrix;
  14654. };
  14655. /**
  14656. * Sort function to order lights for rendering.
  14657. * @param a First Light object to compare to second.
  14658. * @param b Second Light object to compare first.
  14659. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14660. */
  14661. Light.compareLightsPriority = function (a, b) {
  14662. //shadow-casting lights have priority over non-shadow-casting lights
  14663. //the renderPrioirty is a secondary sort criterion
  14664. if (a.shadowEnabled !== b.shadowEnabled) {
  14665. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14666. }
  14667. return b.renderPriority - a.renderPriority;
  14668. };
  14669. /**
  14670. * Disposes the light.
  14671. */
  14672. Light.prototype.dispose = function () {
  14673. if (this._shadowGenerator) {
  14674. this._shadowGenerator.dispose();
  14675. this._shadowGenerator = null;
  14676. }
  14677. // Animations
  14678. this.getScene().stopAnimation(this);
  14679. // Remove from meshes
  14680. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14681. var mesh = _a[_i];
  14682. mesh._removeLightSource(this);
  14683. }
  14684. this._uniformBuffer.dispose();
  14685. // Remove from scene
  14686. this.getScene().removeLight(this);
  14687. _super.prototype.dispose.call(this);
  14688. };
  14689. /**
  14690. * Returns the light type ID (integer).
  14691. */
  14692. Light.prototype.getTypeID = function () {
  14693. return 0;
  14694. };
  14695. /**
  14696. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14697. */
  14698. Light.prototype.getScaledIntensity = function () {
  14699. return this._photometricScale * this.intensity;
  14700. };
  14701. /**
  14702. * Returns a new Light object, named "name", from the current one.
  14703. */
  14704. Light.prototype.clone = function (name) {
  14705. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14706. };
  14707. /**
  14708. * Serializes the current light into a Serialization object.
  14709. * Returns the serialized object.
  14710. */
  14711. Light.prototype.serialize = function () {
  14712. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14713. // Type
  14714. serializationObject.type = this.getTypeID();
  14715. // Parent
  14716. if (this.parent) {
  14717. serializationObject.parentId = this.parent.id;
  14718. }
  14719. // Inclusion / exclusions
  14720. if (this.excludedMeshes.length > 0) {
  14721. serializationObject.excludedMeshesIds = [];
  14722. this.excludedMeshes.forEach(function (mesh) {
  14723. serializationObject.excludedMeshesIds.push(mesh.id);
  14724. });
  14725. }
  14726. if (this.includedOnlyMeshes.length > 0) {
  14727. serializationObject.includedOnlyMeshesIds = [];
  14728. this.includedOnlyMeshes.forEach(function (mesh) {
  14729. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14730. });
  14731. }
  14732. // Animations
  14733. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14734. serializationObject.ranges = this.serializeAnimationRanges();
  14735. return serializationObject;
  14736. };
  14737. /**
  14738. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14739. * This new light is named "name" and added to the passed scene.
  14740. */
  14741. Light.GetConstructorFromName = function (type, name, scene) {
  14742. switch (type) {
  14743. case 0:
  14744. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14745. case 1:
  14746. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14747. case 2:
  14748. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14749. case 3:
  14750. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14751. }
  14752. };
  14753. /**
  14754. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14755. */
  14756. Light.Parse = function (parsedLight, scene) {
  14757. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14758. // Inclusion / exclusions
  14759. if (parsedLight.excludedMeshesIds) {
  14760. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14761. }
  14762. if (parsedLight.includedOnlyMeshesIds) {
  14763. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14764. }
  14765. // Parent
  14766. if (parsedLight.parentId) {
  14767. light._waitingParentId = parsedLight.parentId;
  14768. }
  14769. // Animations
  14770. if (parsedLight.animations) {
  14771. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14772. var parsedAnimation = parsedLight.animations[animationIndex];
  14773. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14774. }
  14775. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14776. }
  14777. if (parsedLight.autoAnimate) {
  14778. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14779. }
  14780. return light;
  14781. };
  14782. Light.prototype._hookArrayForExcluded = function (array) {
  14783. var _this = this;
  14784. var oldPush = array.push;
  14785. array.push = function () {
  14786. var items = [];
  14787. for (var _i = 0; _i < arguments.length; _i++) {
  14788. items[_i] = arguments[_i];
  14789. }
  14790. var result = oldPush.apply(array, items);
  14791. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14792. var item = items_1[_a];
  14793. item._resyncLighSource(_this);
  14794. }
  14795. return result;
  14796. };
  14797. var oldSplice = array.splice;
  14798. array.splice = function (index, deleteCount) {
  14799. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14800. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14801. var item = deleted_1[_i];
  14802. item._resyncLighSource(_this);
  14803. }
  14804. return deleted;
  14805. };
  14806. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14807. var item = array_1[_i];
  14808. item._resyncLighSource(this);
  14809. }
  14810. };
  14811. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14812. var _this = this;
  14813. var oldPush = array.push;
  14814. array.push = function () {
  14815. var items = [];
  14816. for (var _i = 0; _i < arguments.length; _i++) {
  14817. items[_i] = arguments[_i];
  14818. }
  14819. var result = oldPush.apply(array, items);
  14820. _this._resyncMeshes();
  14821. return result;
  14822. };
  14823. var oldSplice = array.splice;
  14824. array.splice = function (index, deleteCount) {
  14825. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14826. _this._resyncMeshes();
  14827. return deleted;
  14828. };
  14829. this._resyncMeshes();
  14830. };
  14831. Light.prototype._resyncMeshes = function () {
  14832. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14833. var mesh = _a[_i];
  14834. mesh._resyncLighSource(this);
  14835. }
  14836. };
  14837. Light.prototype._markMeshesAsLightDirty = function () {
  14838. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14839. var mesh = _a[_i];
  14840. if (mesh._lightSources.indexOf(this) !== -1) {
  14841. mesh._markSubMeshesAsLightDirty();
  14842. }
  14843. }
  14844. };
  14845. /**
  14846. * Recomputes the cached photometric scale if needed.
  14847. */
  14848. Light.prototype._computePhotometricScale = function () {
  14849. this._photometricScale = this._getPhotometricScale();
  14850. this.getScene().resetCachedMaterial();
  14851. };
  14852. /**
  14853. * Returns the Photometric Scale according to the light type and intensity mode.
  14854. */
  14855. Light.prototype._getPhotometricScale = function () {
  14856. var photometricScale = 0.0;
  14857. var lightTypeID = this.getTypeID();
  14858. //get photometric mode
  14859. var photometricMode = this.intensityMode;
  14860. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14861. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14862. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14863. }
  14864. else {
  14865. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14866. }
  14867. }
  14868. //compute photometric scale
  14869. switch (lightTypeID) {
  14870. case Light.LIGHTTYPEID_POINTLIGHT:
  14871. case Light.LIGHTTYPEID_SPOTLIGHT:
  14872. switch (photometricMode) {
  14873. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14874. photometricScale = 1.0 / (4.0 * Math.PI);
  14875. break;
  14876. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14877. photometricScale = 1.0;
  14878. break;
  14879. case Light.INTENSITYMODE_LUMINANCE:
  14880. photometricScale = this.radius * this.radius;
  14881. break;
  14882. }
  14883. break;
  14884. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14885. switch (photometricMode) {
  14886. case Light.INTENSITYMODE_ILLUMINANCE:
  14887. photometricScale = 1.0;
  14888. break;
  14889. case Light.INTENSITYMODE_LUMINANCE:
  14890. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14891. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14892. var apexAngleRadians = this.radius;
  14893. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14894. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14895. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14896. photometricScale = solidAngle;
  14897. break;
  14898. }
  14899. break;
  14900. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14901. // No fall off in hemisperic light.
  14902. photometricScale = 1.0;
  14903. break;
  14904. }
  14905. return photometricScale;
  14906. };
  14907. Light.prototype._reorderLightsInScene = function () {
  14908. var scene = this.getScene();
  14909. if (this.renderPriority != 0) {
  14910. scene.requireLightSorting = true;
  14911. }
  14912. this.getScene().sortLightsByPriority();
  14913. };
  14914. //lightmapMode Consts
  14915. Light._LIGHTMAP_DEFAULT = 0;
  14916. Light._LIGHTMAP_SPECULAR = 1;
  14917. Light._LIGHTMAP_SHADOWSONLY = 2;
  14918. // Intensity Mode Consts
  14919. Light._INTENSITYMODE_AUTOMATIC = 0;
  14920. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14921. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14922. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14923. Light._INTENSITYMODE_LUMINANCE = 4;
  14924. // Light types ids const.
  14925. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14926. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14927. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14928. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14929. __decorate([
  14930. BABYLON.serializeAsColor3()
  14931. ], Light.prototype, "diffuse", void 0);
  14932. __decorate([
  14933. BABYLON.serializeAsColor3()
  14934. ], Light.prototype, "specular", void 0);
  14935. __decorate([
  14936. BABYLON.serialize()
  14937. ], Light.prototype, "intensity", void 0);
  14938. __decorate([
  14939. BABYLON.serialize()
  14940. ], Light.prototype, "range", void 0);
  14941. __decorate([
  14942. BABYLON.serialize()
  14943. ], Light.prototype, "intensityMode", null);
  14944. __decorate([
  14945. BABYLON.serialize()
  14946. ], Light.prototype, "radius", null);
  14947. __decorate([
  14948. BABYLON.serialize()
  14949. ], Light.prototype, "_renderPriority", void 0);
  14950. __decorate([
  14951. BABYLON.expandToProperty("_reorderLightsInScene")
  14952. ], Light.prototype, "renderPriority", void 0);
  14953. __decorate([
  14954. BABYLON.serialize()
  14955. ], Light.prototype, "shadowEnabled", void 0);
  14956. __decorate([
  14957. BABYLON.serialize("excludeWithLayerMask")
  14958. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14959. __decorate([
  14960. BABYLON.serialize("includeOnlyWithLayerMask")
  14961. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14962. __decorate([
  14963. BABYLON.serialize("lightmapMode")
  14964. ], Light.prototype, "_lightmapMode", void 0);
  14965. return Light;
  14966. }(BABYLON.Node));
  14967. BABYLON.Light = Light;
  14968. })(BABYLON || (BABYLON = {}));
  14969. //# sourceMappingURL=babylon.light.js.map
  14970. var BABYLON;
  14971. (function (BABYLON) {
  14972. var Camera = (function (_super) {
  14973. __extends(Camera, _super);
  14974. function Camera(name, position, scene) {
  14975. var _this = _super.call(this, name, scene) || this;
  14976. _this.upVector = BABYLON.Vector3.Up();
  14977. _this.orthoLeft = null;
  14978. _this.orthoRight = null;
  14979. _this.orthoBottom = null;
  14980. _this.orthoTop = null;
  14981. _this.fov = 0.8;
  14982. _this.minZ = 1;
  14983. _this.maxZ = 10000.0;
  14984. _this.inertia = 0.9;
  14985. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14986. _this.isIntermediate = false;
  14987. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14988. _this.layerMask = 0x0FFFFFFF;
  14989. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14990. // Camera rig members
  14991. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14992. _this._rigCameras = new Array();
  14993. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14994. _this._skipRendering = false;
  14995. _this.customRenderTargets = new Array();
  14996. // Observables
  14997. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14998. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14999. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15000. _this.onRestoreStateObservable = new BABYLON.Observable();
  15001. // Cache
  15002. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15003. _this._projectionMatrix = new BABYLON.Matrix();
  15004. _this._doNotComputeProjectionMatrix = false;
  15005. _this._postProcesses = new Array();
  15006. _this._transformMatrix = BABYLON.Matrix.Zero();
  15007. _this._activeMeshes = new BABYLON.SmartArray(256);
  15008. _this._globalPosition = BABYLON.Vector3.Zero();
  15009. _this._refreshFrustumPlanes = true;
  15010. _this.getScene().addCamera(_this);
  15011. if (!_this.getScene().activeCamera) {
  15012. _this.getScene().activeCamera = _this;
  15013. }
  15014. _this.position = position;
  15015. return _this;
  15016. }
  15017. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15018. get: function () {
  15019. return Camera._PERSPECTIVE_CAMERA;
  15020. },
  15021. enumerable: true,
  15022. configurable: true
  15023. });
  15024. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15025. get: function () {
  15026. return Camera._ORTHOGRAPHIC_CAMERA;
  15027. },
  15028. enumerable: true,
  15029. configurable: true
  15030. });
  15031. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15032. get: function () {
  15033. return Camera._FOVMODE_VERTICAL_FIXED;
  15034. },
  15035. enumerable: true,
  15036. configurable: true
  15037. });
  15038. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15039. get: function () {
  15040. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15041. },
  15042. enumerable: true,
  15043. configurable: true
  15044. });
  15045. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15046. get: function () {
  15047. return Camera._RIG_MODE_NONE;
  15048. },
  15049. enumerable: true,
  15050. configurable: true
  15051. });
  15052. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15053. get: function () {
  15054. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15055. },
  15056. enumerable: true,
  15057. configurable: true
  15058. });
  15059. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15060. get: function () {
  15061. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15062. },
  15063. enumerable: true,
  15064. configurable: true
  15065. });
  15066. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15067. get: function () {
  15068. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15069. },
  15070. enumerable: true,
  15071. configurable: true
  15072. });
  15073. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15074. get: function () {
  15075. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15076. },
  15077. enumerable: true,
  15078. configurable: true
  15079. });
  15080. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15081. get: function () {
  15082. return Camera._RIG_MODE_VR;
  15083. },
  15084. enumerable: true,
  15085. configurable: true
  15086. });
  15087. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15088. get: function () {
  15089. return Camera._RIG_MODE_WEBVR;
  15090. },
  15091. enumerable: true,
  15092. configurable: true
  15093. });
  15094. /**
  15095. * Store current camera state (fov, position, etc..)
  15096. */
  15097. Camera.prototype.storeState = function () {
  15098. this._stateStored = true;
  15099. this._storedFov = this.fov;
  15100. return this;
  15101. };
  15102. /**
  15103. * Restores the camera state values if it has been stored. You must call storeState() first
  15104. */
  15105. Camera.prototype._restoreStateValues = function () {
  15106. if (!this._stateStored) {
  15107. return false;
  15108. }
  15109. this.fov = this._storedFov;
  15110. return true;
  15111. };
  15112. /**
  15113. * Restored camera state. You must call storeState() first
  15114. */
  15115. Camera.prototype.restoreState = function () {
  15116. if (this._restoreStateValues()) {
  15117. this.onRestoreStateObservable.notifyObservers(this);
  15118. return true;
  15119. }
  15120. return false;
  15121. };
  15122. Camera.prototype.getClassName = function () {
  15123. return "Camera";
  15124. };
  15125. /**
  15126. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15127. */
  15128. Camera.prototype.toString = function (fullDetails) {
  15129. var ret = "Name: " + this.name;
  15130. ret += ", type: " + this.getClassName();
  15131. if (this.animations) {
  15132. for (var i = 0; i < this.animations.length; i++) {
  15133. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15134. }
  15135. }
  15136. if (fullDetails) {
  15137. }
  15138. return ret;
  15139. };
  15140. Object.defineProperty(Camera.prototype, "globalPosition", {
  15141. get: function () {
  15142. return this._globalPosition;
  15143. },
  15144. enumerable: true,
  15145. configurable: true
  15146. });
  15147. Camera.prototype.getActiveMeshes = function () {
  15148. return this._activeMeshes;
  15149. };
  15150. Camera.prototype.isActiveMesh = function (mesh) {
  15151. return (this._activeMeshes.indexOf(mesh) !== -1);
  15152. };
  15153. //Cache
  15154. Camera.prototype._initCache = function () {
  15155. _super.prototype._initCache.call(this);
  15156. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15157. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15158. this._cache.mode = undefined;
  15159. this._cache.minZ = undefined;
  15160. this._cache.maxZ = undefined;
  15161. this._cache.fov = undefined;
  15162. this._cache.fovMode = undefined;
  15163. this._cache.aspectRatio = undefined;
  15164. this._cache.orthoLeft = undefined;
  15165. this._cache.orthoRight = undefined;
  15166. this._cache.orthoBottom = undefined;
  15167. this._cache.orthoTop = undefined;
  15168. this._cache.renderWidth = undefined;
  15169. this._cache.renderHeight = undefined;
  15170. };
  15171. Camera.prototype._updateCache = function (ignoreParentClass) {
  15172. if (!ignoreParentClass) {
  15173. _super.prototype._updateCache.call(this);
  15174. }
  15175. var engine = this.getEngine();
  15176. this._cache.position.copyFrom(this.position);
  15177. this._cache.upVector.copyFrom(this.upVector);
  15178. };
  15179. // Synchronized
  15180. Camera.prototype._isSynchronized = function () {
  15181. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15182. };
  15183. Camera.prototype._isSynchronizedViewMatrix = function () {
  15184. if (!_super.prototype._isSynchronized.call(this))
  15185. return false;
  15186. return this._cache.position.equals(this.position)
  15187. && this._cache.upVector.equals(this.upVector)
  15188. && this.isSynchronizedWithParent();
  15189. };
  15190. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15191. var check = this._cache.mode === this.mode
  15192. && this._cache.minZ === this.minZ
  15193. && this._cache.maxZ === this.maxZ;
  15194. if (!check) {
  15195. return false;
  15196. }
  15197. var engine = this.getEngine();
  15198. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15199. check = this._cache.fov === this.fov
  15200. && this._cache.fovMode === this.fovMode
  15201. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15202. }
  15203. else {
  15204. check = this._cache.orthoLeft === this.orthoLeft
  15205. && this._cache.orthoRight === this.orthoRight
  15206. && this._cache.orthoBottom === this.orthoBottom
  15207. && this._cache.orthoTop === this.orthoTop
  15208. && this._cache.renderWidth === engine.getRenderWidth()
  15209. && this._cache.renderHeight === engine.getRenderHeight();
  15210. }
  15211. return check;
  15212. };
  15213. // Controls
  15214. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15215. };
  15216. Camera.prototype.detachControl = function (element) {
  15217. };
  15218. Camera.prototype.update = function () {
  15219. this._checkInputs();
  15220. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15221. this._updateRigCameras();
  15222. }
  15223. };
  15224. Camera.prototype._checkInputs = function () {
  15225. this.onAfterCheckInputsObservable.notifyObservers(this);
  15226. };
  15227. Object.defineProperty(Camera.prototype, "rigCameras", {
  15228. get: function () {
  15229. return this._rigCameras;
  15230. },
  15231. enumerable: true,
  15232. configurable: true
  15233. });
  15234. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15235. get: function () {
  15236. return this._rigPostProcess;
  15237. },
  15238. enumerable: true,
  15239. configurable: true
  15240. });
  15241. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15242. // invalidate framebuffer
  15243. if (this._postProcesses.length > 0) {
  15244. this._postProcesses[0].markTextureDirty();
  15245. }
  15246. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15247. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15248. var cam = this._rigCameras[i];
  15249. var rigPostProcess = cam._rigPostProcess;
  15250. // for VR rig, there does not have to be a post process
  15251. if (rigPostProcess) {
  15252. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15253. if (isPass) {
  15254. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15255. cam.isIntermediate = this._postProcesses.length === 0;
  15256. }
  15257. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15258. rigPostProcess.markTextureDirty();
  15259. }
  15260. else {
  15261. cam._postProcesses = this._postProcesses.slice(0);
  15262. }
  15263. }
  15264. };
  15265. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15266. if (insertAt === void 0) { insertAt = null; }
  15267. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15268. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15269. return 0;
  15270. }
  15271. if (insertAt == null || insertAt < 0) {
  15272. this._postProcesses.push(postProcess);
  15273. }
  15274. else {
  15275. this._postProcesses.splice(insertAt, 0, postProcess);
  15276. }
  15277. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15278. return this._postProcesses.indexOf(postProcess);
  15279. };
  15280. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15281. if (atIndices === void 0) { atIndices = null; }
  15282. var result = [];
  15283. var i;
  15284. var index;
  15285. if (!atIndices) {
  15286. var idx = this._postProcesses.indexOf(postProcess);
  15287. if (idx !== -1) {
  15288. this._postProcesses.splice(idx, 1);
  15289. }
  15290. }
  15291. else {
  15292. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15293. // iterate descending, so can just splice as we go
  15294. for (i = atIndices.length - 1; i >= 0; i--) {
  15295. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15296. result.push(i);
  15297. continue;
  15298. }
  15299. index = atIndices[i];
  15300. this._postProcesses.splice(index, 1);
  15301. }
  15302. }
  15303. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15304. return result;
  15305. };
  15306. Camera.prototype.getWorldMatrix = function () {
  15307. if (!this._worldMatrix) {
  15308. this._worldMatrix = BABYLON.Matrix.Identity();
  15309. }
  15310. var viewMatrix = this.getViewMatrix();
  15311. viewMatrix.invertToRef(this._worldMatrix);
  15312. return this._worldMatrix;
  15313. };
  15314. Camera.prototype._getViewMatrix = function () {
  15315. return BABYLON.Matrix.Identity();
  15316. };
  15317. Camera.prototype.getViewMatrix = function (force) {
  15318. if (!force && this._isSynchronizedViewMatrix()) {
  15319. return this._computedViewMatrix;
  15320. }
  15321. this.updateCache();
  15322. this._computedViewMatrix = this._getViewMatrix();
  15323. this._currentRenderId = this.getScene().getRenderId();
  15324. this._refreshFrustumPlanes = true;
  15325. if (!this.parent || !this.parent.getWorldMatrix) {
  15326. this._globalPosition.copyFrom(this.position);
  15327. }
  15328. else {
  15329. if (!this._worldMatrix) {
  15330. this._worldMatrix = BABYLON.Matrix.Identity();
  15331. }
  15332. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15333. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15334. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15335. this._computedViewMatrix.invert();
  15336. this._markSyncedWithParent();
  15337. }
  15338. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15339. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15340. }
  15341. this.onViewMatrixChangedObservable.notifyObservers(this);
  15342. return this._computedViewMatrix;
  15343. };
  15344. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15345. this._doNotComputeProjectionMatrix = true;
  15346. if (projection !== undefined) {
  15347. this._projectionMatrix = projection;
  15348. }
  15349. };
  15350. ;
  15351. Camera.prototype.unfreezeProjectionMatrix = function () {
  15352. this._doNotComputeProjectionMatrix = false;
  15353. };
  15354. ;
  15355. Camera.prototype.getProjectionMatrix = function (force) {
  15356. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15357. return this._projectionMatrix;
  15358. }
  15359. // Cache
  15360. this._cache.mode = this.mode;
  15361. this._cache.minZ = this.minZ;
  15362. this._cache.maxZ = this.maxZ;
  15363. // Matrix
  15364. this._refreshFrustumPlanes = true;
  15365. var engine = this.getEngine();
  15366. var scene = this.getScene();
  15367. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15368. this._cache.fov = this.fov;
  15369. this._cache.fovMode = this.fovMode;
  15370. this._cache.aspectRatio = engine.getAspectRatio(this);
  15371. if (this.minZ <= 0) {
  15372. this.minZ = 0.1;
  15373. }
  15374. if (scene.useRightHandedSystem) {
  15375. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15376. }
  15377. else {
  15378. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15379. }
  15380. }
  15381. else {
  15382. var halfWidth = engine.getRenderWidth() / 2.0;
  15383. var halfHeight = engine.getRenderHeight() / 2.0;
  15384. if (scene.useRightHandedSystem) {
  15385. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15386. }
  15387. else {
  15388. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15389. }
  15390. this._cache.orthoLeft = this.orthoLeft;
  15391. this._cache.orthoRight = this.orthoRight;
  15392. this._cache.orthoBottom = this.orthoBottom;
  15393. this._cache.orthoTop = this.orthoTop;
  15394. this._cache.renderWidth = engine.getRenderWidth();
  15395. this._cache.renderHeight = engine.getRenderHeight();
  15396. }
  15397. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15398. return this._projectionMatrix;
  15399. };
  15400. Camera.prototype.getTranformationMatrix = function () {
  15401. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15402. return this._transformMatrix;
  15403. };
  15404. Camera.prototype.updateFrustumPlanes = function () {
  15405. if (!this._refreshFrustumPlanes) {
  15406. return;
  15407. }
  15408. this.getTranformationMatrix();
  15409. if (!this._frustumPlanes) {
  15410. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15411. }
  15412. else {
  15413. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15414. }
  15415. this._refreshFrustumPlanes = false;
  15416. };
  15417. Camera.prototype.isInFrustum = function (target) {
  15418. this.updateFrustumPlanes();
  15419. return target.isInFrustum(this._frustumPlanes);
  15420. };
  15421. Camera.prototype.isCompletelyInFrustum = function (target) {
  15422. this.updateFrustumPlanes();
  15423. return target.isCompletelyInFrustum(this._frustumPlanes);
  15424. };
  15425. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15426. if (length === void 0) { length = 100; }
  15427. if (!transform) {
  15428. transform = this.getWorldMatrix();
  15429. }
  15430. if (!origin) {
  15431. origin = this.position;
  15432. }
  15433. var forward = new BABYLON.Vector3(0, 0, 1);
  15434. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15435. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15436. return new BABYLON.Ray(origin, direction, length);
  15437. };
  15438. Camera.prototype.dispose = function () {
  15439. // Observables
  15440. this.onViewMatrixChangedObservable.clear();
  15441. this.onProjectionMatrixChangedObservable.clear();
  15442. this.onAfterCheckInputsObservable.clear();
  15443. this.onRestoreStateObservable.clear();
  15444. // Inputs
  15445. if (this.inputs) {
  15446. this.inputs.clear();
  15447. }
  15448. // Animations
  15449. this.getScene().stopAnimation(this);
  15450. // Remove from scene
  15451. this.getScene().removeCamera(this);
  15452. while (this._rigCameras.length > 0) {
  15453. this._rigCameras.pop().dispose();
  15454. }
  15455. // Postprocesses
  15456. var i = this._postProcesses.length;
  15457. while (--i >= 0) {
  15458. this._postProcesses[i].dispose(this);
  15459. }
  15460. // Render targets
  15461. var i = this.customRenderTargets.length;
  15462. while (--i >= 0) {
  15463. this.customRenderTargets[i].dispose();
  15464. }
  15465. this.customRenderTargets = [];
  15466. // Active Meshes
  15467. this._activeMeshes.dispose();
  15468. _super.prototype.dispose.call(this);
  15469. };
  15470. Object.defineProperty(Camera.prototype, "leftCamera", {
  15471. // ---- Camera rigs section ----
  15472. get: function () {
  15473. if (this._rigCameras.length < 1) {
  15474. return undefined;
  15475. }
  15476. return this._rigCameras[0];
  15477. },
  15478. enumerable: true,
  15479. configurable: true
  15480. });
  15481. Object.defineProperty(Camera.prototype, "rightCamera", {
  15482. get: function () {
  15483. if (this._rigCameras.length < 2) {
  15484. return undefined;
  15485. }
  15486. return this._rigCameras[1];
  15487. },
  15488. enumerable: true,
  15489. configurable: true
  15490. });
  15491. Camera.prototype.getLeftTarget = function () {
  15492. if (this._rigCameras.length < 1) {
  15493. return undefined;
  15494. }
  15495. return this._rigCameras[0].getTarget();
  15496. };
  15497. Camera.prototype.getRightTarget = function () {
  15498. if (this._rigCameras.length < 2) {
  15499. return undefined;
  15500. }
  15501. return this._rigCameras[1].getTarget();
  15502. };
  15503. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15504. while (this._rigCameras.length > 0) {
  15505. this._rigCameras.pop().dispose();
  15506. }
  15507. this.cameraRigMode = mode;
  15508. this._cameraRigParams = {};
  15509. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15510. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15511. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15512. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15513. // create the rig cameras, unless none
  15514. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15515. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15516. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15517. }
  15518. switch (this.cameraRigMode) {
  15519. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15520. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15521. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15522. break;
  15523. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15524. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15525. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15526. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15527. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15528. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15529. break;
  15530. case Camera.RIG_MODE_VR:
  15531. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15532. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15533. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15534. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15535. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15536. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15537. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15538. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15539. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15540. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15541. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15542. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15543. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15544. if (metrics.compensateDistortion) {
  15545. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15546. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15547. }
  15548. break;
  15549. case Camera.RIG_MODE_WEBVR:
  15550. if (rigParams.vrDisplay) {
  15551. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15552. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15553. //Left eye
  15554. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15555. this._rigCameras[0].setCameraRigParameter("left", true);
  15556. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15557. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15558. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15559. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15560. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15561. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15562. this._rigCameras[0].parent = this;
  15563. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15564. //Right eye
  15565. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15566. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15567. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15568. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15569. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15570. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15571. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15572. this._rigCameras[1].parent = this;
  15573. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15574. if (Camera.UseAlternateWebVRRendering) {
  15575. this._rigCameras[1]._skipRendering = true;
  15576. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  15577. }
  15578. }
  15579. break;
  15580. }
  15581. this._cascadePostProcessesToRigCams();
  15582. this.update();
  15583. };
  15584. Camera.prototype._getVRProjectionMatrix = function () {
  15585. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15586. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15587. return this._projectionMatrix;
  15588. };
  15589. Camera.prototype._updateCameraRotationMatrix = function () {
  15590. //Here for WebVR
  15591. };
  15592. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15593. //Here for WebVR
  15594. };
  15595. /**
  15596. * This function MUST be overwritten by the different WebVR cameras available.
  15597. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15598. */
  15599. Camera.prototype._getWebVRProjectionMatrix = function () {
  15600. return BABYLON.Matrix.Identity();
  15601. };
  15602. /**
  15603. * This function MUST be overwritten by the different WebVR cameras available.
  15604. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15605. */
  15606. Camera.prototype._getWebVRViewMatrix = function () {
  15607. return BABYLON.Matrix.Identity();
  15608. };
  15609. Camera.prototype.setCameraRigParameter = function (name, value) {
  15610. if (!this._cameraRigParams) {
  15611. this._cameraRigParams = {};
  15612. }
  15613. this._cameraRigParams[name] = value;
  15614. //provisionnally:
  15615. if (name === "interaxialDistance") {
  15616. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15617. }
  15618. };
  15619. /**
  15620. * needs to be overridden by children so sub has required properties to be copied
  15621. */
  15622. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15623. return null;
  15624. };
  15625. /**
  15626. * May need to be overridden by children
  15627. */
  15628. Camera.prototype._updateRigCameras = function () {
  15629. for (var i = 0; i < this._rigCameras.length; i++) {
  15630. this._rigCameras[i].minZ = this.minZ;
  15631. this._rigCameras[i].maxZ = this.maxZ;
  15632. this._rigCameras[i].fov = this.fov;
  15633. }
  15634. // only update viewport when ANAGLYPH
  15635. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15636. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15637. }
  15638. };
  15639. Camera.prototype._setupInputs = function () {
  15640. };
  15641. Camera.prototype.serialize = function () {
  15642. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15643. // Type
  15644. serializationObject.type = this.getClassName();
  15645. // Parent
  15646. if (this.parent) {
  15647. serializationObject.parentId = this.parent.id;
  15648. }
  15649. if (this.inputs) {
  15650. this.inputs.serialize(serializationObject);
  15651. }
  15652. // Animations
  15653. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15654. serializationObject.ranges = this.serializeAnimationRanges();
  15655. return serializationObject;
  15656. };
  15657. Camera.prototype.clone = function (name) {
  15658. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15659. };
  15660. Camera.prototype.getDirection = function (localAxis) {
  15661. var result = BABYLON.Vector3.Zero();
  15662. this.getDirectionToRef(localAxis, result);
  15663. return result;
  15664. };
  15665. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15666. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15667. };
  15668. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15669. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15670. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15671. switch (type) {
  15672. case "ArcRotateCamera":
  15673. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15674. case "DeviceOrientationCamera":
  15675. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15676. case "FollowCamera":
  15677. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15678. case "ArcFollowCamera":
  15679. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15680. case "GamepadCamera":
  15681. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15682. case "TouchCamera":
  15683. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15684. case "VirtualJoysticksCamera":
  15685. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15686. case "WebVRFreeCamera":
  15687. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15688. case "WebVRGamepadCamera":
  15689. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15690. case "VRDeviceOrientationFreeCamera":
  15691. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15692. case "VRDeviceOrientationGamepadCamera":
  15693. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15694. case "AnaglyphArcRotateCamera":
  15695. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15696. case "AnaglyphFreeCamera":
  15697. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15698. case "AnaglyphGamepadCamera":
  15699. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15700. case "AnaglyphUniversalCamera":
  15701. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15702. case "StereoscopicArcRotateCamera":
  15703. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15704. case "StereoscopicFreeCamera":
  15705. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15706. case "StereoscopicGamepadCamera":
  15707. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15708. case "StereoscopicUniversalCamera":
  15709. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15710. case "FreeCamera":// Forcing Universal here
  15711. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15712. default:// Universal Camera is the default value
  15713. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15714. }
  15715. };
  15716. Camera.Parse = function (parsedCamera, scene) {
  15717. var type = parsedCamera.type;
  15718. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15719. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15720. // Parent
  15721. if (parsedCamera.parentId) {
  15722. camera._waitingParentId = parsedCamera.parentId;
  15723. }
  15724. //If camera has an input manager, let it parse inputs settings
  15725. if (camera.inputs) {
  15726. camera.inputs.parse(parsedCamera);
  15727. camera._setupInputs();
  15728. }
  15729. if (camera.setPosition) {
  15730. camera.position.copyFromFloats(0, 0, 0);
  15731. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15732. }
  15733. // Target
  15734. if (parsedCamera.target) {
  15735. if (camera.setTarget) {
  15736. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15737. }
  15738. }
  15739. // Apply 3d rig, when found
  15740. if (parsedCamera.cameraRigMode) {
  15741. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15742. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15743. }
  15744. // Animations
  15745. if (parsedCamera.animations) {
  15746. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15747. var parsedAnimation = parsedCamera.animations[animationIndex];
  15748. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15749. }
  15750. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15751. }
  15752. if (parsedCamera.autoAnimate) {
  15753. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15754. }
  15755. return camera;
  15756. };
  15757. // Statics
  15758. Camera._PERSPECTIVE_CAMERA = 0;
  15759. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15760. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15761. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15762. Camera._RIG_MODE_NONE = 0;
  15763. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15764. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15765. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15766. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15767. Camera._RIG_MODE_VR = 20;
  15768. Camera._RIG_MODE_WEBVR = 21;
  15769. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15770. Camera.UseAlternateWebVRRendering = false;
  15771. __decorate([
  15772. BABYLON.serializeAsVector3()
  15773. ], Camera.prototype, "position", void 0);
  15774. __decorate([
  15775. BABYLON.serializeAsVector3()
  15776. ], Camera.prototype, "upVector", void 0);
  15777. __decorate([
  15778. BABYLON.serialize()
  15779. ], Camera.prototype, "orthoLeft", void 0);
  15780. __decorate([
  15781. BABYLON.serialize()
  15782. ], Camera.prototype, "orthoRight", void 0);
  15783. __decorate([
  15784. BABYLON.serialize()
  15785. ], Camera.prototype, "orthoBottom", void 0);
  15786. __decorate([
  15787. BABYLON.serialize()
  15788. ], Camera.prototype, "orthoTop", void 0);
  15789. __decorate([
  15790. BABYLON.serialize()
  15791. ], Camera.prototype, "fov", void 0);
  15792. __decorate([
  15793. BABYLON.serialize()
  15794. ], Camera.prototype, "minZ", void 0);
  15795. __decorate([
  15796. BABYLON.serialize()
  15797. ], Camera.prototype, "maxZ", void 0);
  15798. __decorate([
  15799. BABYLON.serialize()
  15800. ], Camera.prototype, "inertia", void 0);
  15801. __decorate([
  15802. BABYLON.serialize()
  15803. ], Camera.prototype, "mode", void 0);
  15804. __decorate([
  15805. BABYLON.serialize()
  15806. ], Camera.prototype, "layerMask", void 0);
  15807. __decorate([
  15808. BABYLON.serialize()
  15809. ], Camera.prototype, "fovMode", void 0);
  15810. __decorate([
  15811. BABYLON.serialize()
  15812. ], Camera.prototype, "cameraRigMode", void 0);
  15813. __decorate([
  15814. BABYLON.serialize()
  15815. ], Camera.prototype, "interaxialDistance", void 0);
  15816. __decorate([
  15817. BABYLON.serialize()
  15818. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15819. return Camera;
  15820. }(BABYLON.Node));
  15821. BABYLON.Camera = Camera;
  15822. })(BABYLON || (BABYLON = {}));
  15823. //# sourceMappingURL=babylon.camera.js.map
  15824. var BABYLON;
  15825. (function (BABYLON) {
  15826. var RenderingManager = (function () {
  15827. function RenderingManager(scene) {
  15828. this._renderingGroups = new Array();
  15829. this._autoClearDepthStencil = {};
  15830. this._customOpaqueSortCompareFn = {};
  15831. this._customAlphaTestSortCompareFn = {};
  15832. this._customTransparentSortCompareFn = {};
  15833. this._renderinGroupInfo = null;
  15834. this._scene = scene;
  15835. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15836. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15837. }
  15838. }
  15839. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15840. if (depth === void 0) { depth = true; }
  15841. if (stencil === void 0) { stencil = true; }
  15842. if (this._depthStencilBufferAlreadyCleaned) {
  15843. return;
  15844. }
  15845. this._scene.getEngine().clear(null, false, depth, stencil);
  15846. this._depthStencilBufferAlreadyCleaned = true;
  15847. };
  15848. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15849. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15850. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15851. var info = null;
  15852. if (observable) {
  15853. if (!this._renderinGroupInfo) {
  15854. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15855. }
  15856. info = this._renderinGroupInfo;
  15857. info.scene = this._scene;
  15858. info.camera = this._scene.activeCamera;
  15859. }
  15860. // Dispatch sprites
  15861. if (renderSprites) {
  15862. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15863. var manager = this._scene.spriteManagers[index];
  15864. this.dispatchSprites(manager);
  15865. }
  15866. }
  15867. // Render
  15868. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15869. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15870. var renderingGroup = this._renderingGroups[index];
  15871. if (!renderingGroup && !observable)
  15872. continue;
  15873. this._currentIndex = index;
  15874. var renderingGroupMask = 0;
  15875. // Fire PRECLEAR stage
  15876. if (observable) {
  15877. renderingGroupMask = Math.pow(2, index);
  15878. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15879. info.renderingGroupId = index;
  15880. observable.notifyObservers(info, renderingGroupMask);
  15881. }
  15882. // Clear depth/stencil if needed
  15883. if (RenderingManager.AUTOCLEAR) {
  15884. var autoClear = this._autoClearDepthStencil[index];
  15885. if (autoClear && autoClear.autoClear) {
  15886. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15887. }
  15888. }
  15889. if (observable) {
  15890. // Fire PREOPAQUE stage
  15891. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15892. observable.notifyObservers(info, renderingGroupMask);
  15893. // Fire PRETRANSPARENT stage
  15894. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15895. observable.notifyObservers(info, renderingGroupMask);
  15896. }
  15897. if (renderingGroup)
  15898. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15899. // Fire POSTTRANSPARENT stage
  15900. if (observable) {
  15901. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15902. observable.notifyObservers(info, renderingGroupMask);
  15903. }
  15904. }
  15905. };
  15906. RenderingManager.prototype.reset = function () {
  15907. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15908. var renderingGroup = this._renderingGroups[index];
  15909. if (renderingGroup) {
  15910. renderingGroup.prepare();
  15911. }
  15912. }
  15913. };
  15914. RenderingManager.prototype.dispose = function () {
  15915. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15916. var renderingGroup = this._renderingGroups[index];
  15917. if (renderingGroup) {
  15918. renderingGroup.dispose();
  15919. }
  15920. }
  15921. this._renderingGroups.length = 0;
  15922. };
  15923. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15924. if (!this._renderingGroups[renderingGroupId]) {
  15925. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15926. }
  15927. };
  15928. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15929. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15930. this._prepareRenderingGroup(renderingGroupId);
  15931. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15932. };
  15933. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15934. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15935. this._prepareRenderingGroup(renderingGroupId);
  15936. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15937. };
  15938. RenderingManager.prototype.dispatch = function (subMesh) {
  15939. var mesh = subMesh.getMesh();
  15940. var renderingGroupId = mesh.renderingGroupId || 0;
  15941. this._prepareRenderingGroup(renderingGroupId);
  15942. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15943. };
  15944. /**
  15945. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15946. * This allowed control for front to back rendering or reversly depending of the special needs.
  15947. *
  15948. * @param renderingGroupId The rendering group id corresponding to its index
  15949. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15950. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15951. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15952. */
  15953. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15954. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15955. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15956. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15957. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15958. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15959. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15960. if (this._renderingGroups[renderingGroupId]) {
  15961. var group = this._renderingGroups[renderingGroupId];
  15962. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15963. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15964. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15965. }
  15966. };
  15967. /**
  15968. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15969. *
  15970. * @param renderingGroupId The rendering group id corresponding to its index
  15971. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15972. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15973. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15974. */
  15975. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15976. if (depth === void 0) { depth = true; }
  15977. if (stencil === void 0) { stencil = true; }
  15978. this._autoClearDepthStencil[renderingGroupId] = {
  15979. autoClear: autoClearDepthStencil,
  15980. depth: depth,
  15981. stencil: stencil
  15982. };
  15983. };
  15984. /**
  15985. * The max id used for rendering groups (not included)
  15986. */
  15987. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15988. /**
  15989. * The min id used for rendering groups (included)
  15990. */
  15991. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15992. /**
  15993. * Used to globally prevent autoclearing scenes.
  15994. */
  15995. RenderingManager.AUTOCLEAR = true;
  15996. return RenderingManager;
  15997. }());
  15998. BABYLON.RenderingManager = RenderingManager;
  15999. })(BABYLON || (BABYLON = {}));
  16000. //# sourceMappingURL=babylon.renderingManager.js.map
  16001. var BABYLON;
  16002. (function (BABYLON) {
  16003. var RenderingGroup = (function () {
  16004. /**
  16005. * Creates a new rendering group.
  16006. * @param index The rendering group index
  16007. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16008. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16009. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16010. */
  16011. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16012. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16013. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16014. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16015. this.index = index;
  16016. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16017. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16018. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16019. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16020. this._particleSystems = new BABYLON.SmartArray(256);
  16021. this._spriteManagers = new BABYLON.SmartArray(256);
  16022. this._edgesRenderers = new BABYLON.SmartArray(16);
  16023. this._scene = scene;
  16024. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16025. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16026. this.transparentSortCompareFn = transparentSortCompareFn;
  16027. }
  16028. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16029. /**
  16030. * Set the opaque sort comparison function.
  16031. * If null the sub meshes will be render in the order they were created
  16032. */
  16033. set: function (value) {
  16034. this._opaqueSortCompareFn = value;
  16035. if (value) {
  16036. this._renderOpaque = this.renderOpaqueSorted;
  16037. }
  16038. else {
  16039. this._renderOpaque = RenderingGroup.renderUnsorted;
  16040. }
  16041. },
  16042. enumerable: true,
  16043. configurable: true
  16044. });
  16045. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16046. /**
  16047. * Set the alpha test sort comparison function.
  16048. * If null the sub meshes will be render in the order they were created
  16049. */
  16050. set: function (value) {
  16051. this._alphaTestSortCompareFn = value;
  16052. if (value) {
  16053. this._renderAlphaTest = this.renderAlphaTestSorted;
  16054. }
  16055. else {
  16056. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16057. }
  16058. },
  16059. enumerable: true,
  16060. configurable: true
  16061. });
  16062. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16063. /**
  16064. * Set the transparent sort comparison function.
  16065. * If null the sub meshes will be render in the order they were created
  16066. */
  16067. set: function (value) {
  16068. if (value) {
  16069. this._transparentSortCompareFn = value;
  16070. }
  16071. else {
  16072. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16073. }
  16074. this._renderTransparent = this.renderTransparentSorted;
  16075. },
  16076. enumerable: true,
  16077. configurable: true
  16078. });
  16079. /**
  16080. * Render all the sub meshes contained in the group.
  16081. * @param customRenderFunction Used to override the default render behaviour of the group.
  16082. * @returns true if rendered some submeshes.
  16083. */
  16084. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16085. if (customRenderFunction) {
  16086. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16087. return;
  16088. }
  16089. var engine = this._scene.getEngine();
  16090. // Depth only
  16091. if (this._depthOnlySubMeshes.length !== 0) {
  16092. engine.setAlphaTesting(true);
  16093. engine.setColorWrite(false);
  16094. this._renderAlphaTest(this._depthOnlySubMeshes);
  16095. engine.setAlphaTesting(false);
  16096. engine.setColorWrite(true);
  16097. }
  16098. // Opaque
  16099. if (this._opaqueSubMeshes.length !== 0) {
  16100. this._renderOpaque(this._opaqueSubMeshes);
  16101. }
  16102. // Alpha test
  16103. if (this._alphaTestSubMeshes.length !== 0) {
  16104. engine.setAlphaTesting(true);
  16105. this._renderAlphaTest(this._alphaTestSubMeshes);
  16106. engine.setAlphaTesting(false);
  16107. }
  16108. var stencilState = engine.getStencilBuffer();
  16109. engine.setStencilBuffer(false);
  16110. // Sprites
  16111. if (renderSprites) {
  16112. this._renderSprites();
  16113. }
  16114. // Particles
  16115. if (renderParticles) {
  16116. this._renderParticles(activeMeshes);
  16117. }
  16118. if (this.onBeforeTransparentRendering) {
  16119. this.onBeforeTransparentRendering();
  16120. }
  16121. // Transparent
  16122. if (this._transparentSubMeshes.length !== 0) {
  16123. this._renderTransparent(this._transparentSubMeshes);
  16124. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16125. }
  16126. // Set back stencil to false in case it changes before the edge renderer.
  16127. engine.setStencilBuffer(false);
  16128. // Edges
  16129. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16130. this._edgesRenderers.data[edgesRendererIndex].render();
  16131. }
  16132. // Restore Stencil state.
  16133. engine.setStencilBuffer(stencilState);
  16134. };
  16135. /**
  16136. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16137. * @param subMeshes The submeshes to render
  16138. */
  16139. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16140. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16141. };
  16142. /**
  16143. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16144. * @param subMeshes The submeshes to render
  16145. */
  16146. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16147. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16148. };
  16149. /**
  16150. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16151. * @param subMeshes The submeshes to render
  16152. */
  16153. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16154. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16155. };
  16156. /**
  16157. * Renders the submeshes in a specified order.
  16158. * @param subMeshes The submeshes to sort before render
  16159. * @param sortCompareFn The comparison function use to sort
  16160. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16161. * @param transparent Specifies to activate blending if true
  16162. */
  16163. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16164. var subIndex = 0;
  16165. var subMesh;
  16166. for (; subIndex < subMeshes.length; subIndex++) {
  16167. subMesh = subMeshes.data[subIndex];
  16168. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16169. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16170. }
  16171. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16172. sortedArray.sort(sortCompareFn);
  16173. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16174. subMesh = sortedArray[subIndex];
  16175. if (transparent) {
  16176. var material = subMesh.getMaterial();
  16177. if (material.needDepthPrePass) {
  16178. var engine = material.getScene().getEngine();
  16179. engine.setColorWrite(false);
  16180. engine.setAlphaTesting(true);
  16181. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16182. subMesh.render(false);
  16183. engine.setAlphaTesting(false);
  16184. engine.setColorWrite(true);
  16185. }
  16186. }
  16187. subMesh.render(transparent);
  16188. }
  16189. };
  16190. /**
  16191. * Renders the submeshes in the order they were dispatched (no sort applied).
  16192. * @param subMeshes The submeshes to render
  16193. */
  16194. RenderingGroup.renderUnsorted = function (subMeshes) {
  16195. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16196. var submesh = subMeshes.data[subIndex];
  16197. submesh.render(false);
  16198. }
  16199. };
  16200. /**
  16201. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16202. * are rendered back to front if in the same alpha index.
  16203. *
  16204. * @param a The first submesh
  16205. * @param b The second submesh
  16206. * @returns The result of the comparison
  16207. */
  16208. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16209. // Alpha index first
  16210. if (a._alphaIndex > b._alphaIndex) {
  16211. return 1;
  16212. }
  16213. if (a._alphaIndex < b._alphaIndex) {
  16214. return -1;
  16215. }
  16216. // Then distance to camera
  16217. return RenderingGroup.backToFrontSortCompare(a, b);
  16218. };
  16219. /**
  16220. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16221. * are rendered back to front.
  16222. *
  16223. * @param a The first submesh
  16224. * @param b The second submesh
  16225. * @returns The result of the comparison
  16226. */
  16227. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16228. // Then distance to camera
  16229. if (a._distanceToCamera < b._distanceToCamera) {
  16230. return 1;
  16231. }
  16232. if (a._distanceToCamera > b._distanceToCamera) {
  16233. return -1;
  16234. }
  16235. return 0;
  16236. };
  16237. /**
  16238. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16239. * are rendered front to back (prevent overdraw).
  16240. *
  16241. * @param a The first submesh
  16242. * @param b The second submesh
  16243. * @returns The result of the comparison
  16244. */
  16245. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16246. // Then distance to camera
  16247. if (a._distanceToCamera < b._distanceToCamera) {
  16248. return -1;
  16249. }
  16250. if (a._distanceToCamera > b._distanceToCamera) {
  16251. return 1;
  16252. }
  16253. return 0;
  16254. };
  16255. /**
  16256. * Resets the different lists of submeshes to prepare a new frame.
  16257. */
  16258. RenderingGroup.prototype.prepare = function () {
  16259. this._opaqueSubMeshes.reset();
  16260. this._transparentSubMeshes.reset();
  16261. this._alphaTestSubMeshes.reset();
  16262. this._depthOnlySubMeshes.reset();
  16263. this._particleSystems.reset();
  16264. this._spriteManagers.reset();
  16265. this._edgesRenderers.reset();
  16266. };
  16267. RenderingGroup.prototype.dispose = function () {
  16268. this._opaqueSubMeshes.dispose();
  16269. this._transparentSubMeshes.dispose();
  16270. this._alphaTestSubMeshes.dispose();
  16271. this._depthOnlySubMeshes.dispose();
  16272. this._particleSystems.dispose();
  16273. this._spriteManagers.dispose();
  16274. this._edgesRenderers.dispose();
  16275. };
  16276. /**
  16277. * Inserts the submesh in its correct queue depending on its material.
  16278. * @param subMesh The submesh to dispatch
  16279. */
  16280. RenderingGroup.prototype.dispatch = function (subMesh) {
  16281. var material = subMesh.getMaterial();
  16282. var mesh = subMesh.getMesh();
  16283. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16284. this._transparentSubMeshes.push(subMesh);
  16285. }
  16286. else if (material.needAlphaTesting()) {
  16287. if (material.needDepthPrePass) {
  16288. this._depthOnlySubMeshes.push(subMesh);
  16289. }
  16290. this._alphaTestSubMeshes.push(subMesh);
  16291. }
  16292. else {
  16293. if (material.needDepthPrePass) {
  16294. this._depthOnlySubMeshes.push(subMesh);
  16295. }
  16296. this._opaqueSubMeshes.push(subMesh); // Opaque
  16297. }
  16298. if (mesh._edgesRenderer) {
  16299. this._edgesRenderers.push(mesh._edgesRenderer);
  16300. }
  16301. };
  16302. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16303. this._spriteManagers.push(spriteManager);
  16304. };
  16305. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16306. this._particleSystems.push(particleSystem);
  16307. };
  16308. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16309. if (this._particleSystems.length === 0) {
  16310. return;
  16311. }
  16312. // Particles
  16313. var activeCamera = this._scene.activeCamera;
  16314. this._scene._particlesDuration.beginMonitoring();
  16315. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16316. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16317. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16318. continue;
  16319. }
  16320. var emitter = particleSystem.emitter;
  16321. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16322. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16323. }
  16324. }
  16325. this._scene._particlesDuration.endMonitoring(false);
  16326. };
  16327. RenderingGroup.prototype._renderSprites = function () {
  16328. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16329. return;
  16330. }
  16331. // Sprites
  16332. var activeCamera = this._scene.activeCamera;
  16333. this._scene._spritesDuration.beginMonitoring();
  16334. for (var id = 0; id < this._spriteManagers.length; id++) {
  16335. var spriteManager = this._spriteManagers.data[id];
  16336. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16337. spriteManager.render();
  16338. }
  16339. }
  16340. this._scene._spritesDuration.endMonitoring(false);
  16341. };
  16342. return RenderingGroup;
  16343. }());
  16344. BABYLON.RenderingGroup = RenderingGroup;
  16345. })(BABYLON || (BABYLON = {}));
  16346. //# sourceMappingURL=babylon.renderingGroup.js.map
  16347. var BABYLON;
  16348. (function (BABYLON) {
  16349. var ClickInfo = (function () {
  16350. function ClickInfo() {
  16351. this._singleClick = false;
  16352. this._doubleClick = false;
  16353. this._hasSwiped = false;
  16354. this._ignore = false;
  16355. }
  16356. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16357. get: function () {
  16358. return this._singleClick;
  16359. },
  16360. set: function (b) {
  16361. this._singleClick = b;
  16362. },
  16363. enumerable: true,
  16364. configurable: true
  16365. });
  16366. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16367. get: function () {
  16368. return this._doubleClick;
  16369. },
  16370. set: function (b) {
  16371. this._doubleClick = b;
  16372. },
  16373. enumerable: true,
  16374. configurable: true
  16375. });
  16376. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16377. get: function () {
  16378. return this._hasSwiped;
  16379. },
  16380. set: function (b) {
  16381. this._hasSwiped = b;
  16382. },
  16383. enumerable: true,
  16384. configurable: true
  16385. });
  16386. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16387. get: function () {
  16388. return this._ignore;
  16389. },
  16390. set: function (b) {
  16391. this._ignore = b;
  16392. },
  16393. enumerable: true,
  16394. configurable: true
  16395. });
  16396. return ClickInfo;
  16397. }());
  16398. /**
  16399. * This class is used by the onRenderingGroupObservable
  16400. */
  16401. var RenderingGroupInfo = (function () {
  16402. function RenderingGroupInfo() {
  16403. }
  16404. /**
  16405. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16406. * This stage will be fired no matter what
  16407. */
  16408. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16409. /**
  16410. * Called before opaque object are rendered.
  16411. * This stage will be fired only if there's 3D Opaque content to render
  16412. */
  16413. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16414. /**
  16415. * Called after the opaque objects are rendered and before the transparent ones
  16416. * This stage will be fired only if there's 3D transparent content to render
  16417. */
  16418. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16419. /**
  16420. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16421. * This stage will be fired no matter what
  16422. */
  16423. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16424. return RenderingGroupInfo;
  16425. }());
  16426. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16427. /**
  16428. * Represents a scene to be rendered by the engine.
  16429. * @see http://doc.babylonjs.com/page.php?p=21911
  16430. */
  16431. var Scene = (function () {
  16432. /**
  16433. * @constructor
  16434. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16435. */
  16436. function Scene(engine) {
  16437. // Members
  16438. this.autoClear = true;
  16439. this.autoClearDepthAndStencil = true;
  16440. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16441. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16442. this.forceWireframe = false;
  16443. this._forcePointsCloud = false;
  16444. this.forceShowBoundingBoxes = false;
  16445. this.animationsEnabled = true;
  16446. this.constantlyUpdateMeshUnderPointer = false;
  16447. this.hoverCursor = "pointer";
  16448. this.defaultCursor = "";
  16449. // Metadata
  16450. this.metadata = null;
  16451. /**
  16452. * An event triggered when the scene is disposed.
  16453. * @type {BABYLON.Observable}
  16454. */
  16455. this.onDisposeObservable = new BABYLON.Observable();
  16456. /**
  16457. * An event triggered before rendering the scene
  16458. * @type {BABYLON.Observable}
  16459. */
  16460. this.onBeforeRenderObservable = new BABYLON.Observable();
  16461. /**
  16462. * An event triggered after rendering the scene
  16463. * @type {BABYLON.Observable}
  16464. */
  16465. this.onAfterRenderObservable = new BABYLON.Observable();
  16466. /**
  16467. * An event triggered when the scene is ready
  16468. * @type {BABYLON.Observable}
  16469. */
  16470. this.onReadyObservable = new BABYLON.Observable();
  16471. /**
  16472. * An event triggered before rendering a camera
  16473. * @type {BABYLON.Observable}
  16474. */
  16475. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16476. /**
  16477. * An event triggered after rendering a camera
  16478. * @type {BABYLON.Observable}
  16479. */
  16480. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16481. /**
  16482. * An event triggered when a camera is created
  16483. * @type {BABYLON.Observable}
  16484. */
  16485. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16486. /**
  16487. * An event triggered when a camera is removed
  16488. * @type {BABYLON.Observable}
  16489. */
  16490. this.onCameraRemovedObservable = new BABYLON.Observable();
  16491. /**
  16492. * An event triggered when a light is created
  16493. * @type {BABYLON.Observable}
  16494. */
  16495. this.onNewLightAddedObservable = new BABYLON.Observable();
  16496. /**
  16497. * An event triggered when a light is removed
  16498. * @type {BABYLON.Observable}
  16499. */
  16500. this.onLightRemovedObservable = new BABYLON.Observable();
  16501. /**
  16502. * An event triggered when a geometry is created
  16503. * @type {BABYLON.Observable}
  16504. */
  16505. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16506. /**
  16507. * An event triggered when a geometry is removed
  16508. * @type {BABYLON.Observable}
  16509. */
  16510. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16511. /**
  16512. * An event triggered when a mesh is created
  16513. * @type {BABYLON.Observable}
  16514. */
  16515. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16516. /**
  16517. * An event triggered when a mesh is removed
  16518. * @type {BABYLON.Observable}
  16519. */
  16520. this.onMeshRemovedObservable = new BABYLON.Observable();
  16521. /**
  16522. * An event triggered before calculating deterministic simulation step
  16523. * @type {BABYLON.Observable}
  16524. */
  16525. this.onBeforeStepObservable = new BABYLON.Observable();
  16526. /**
  16527. * An event triggered after calculating deterministic simulation step
  16528. * @type {BABYLON.Observable}
  16529. */
  16530. this.onAfterStepObservable = new BABYLON.Observable();
  16531. /**
  16532. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16533. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16534. * 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)
  16535. */
  16536. this.onRenderingGroupObservable = new BABYLON.Observable();
  16537. // Animations
  16538. this.animations = [];
  16539. /**
  16540. * 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).
  16541. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16542. */
  16543. this.onPrePointerObservable = new BABYLON.Observable();
  16544. /**
  16545. * Observable event triggered each time an input event is received from the rendering canvas
  16546. */
  16547. this.onPointerObservable = new BABYLON.Observable();
  16548. this._meshPickProceed = false;
  16549. this._previousHasSwiped = false;
  16550. this._currentPickResult = null;
  16551. this._previousPickResult = null;
  16552. this._isButtonPressed = false;
  16553. this._doubleClickOccured = false;
  16554. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16555. this.cameraToUseForPointers = null;
  16556. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16557. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16558. this._startingPointerTime = 0;
  16559. this._previousStartingPointerTime = 0;
  16560. // Deterministic lockstep
  16561. this._timeAccumulator = 0;
  16562. this._currentStepId = 0;
  16563. this._currentInternalStep = 0;
  16564. // Keyboard
  16565. /**
  16566. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16567. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16568. */
  16569. this.onPreKeyboardObservable = new BABYLON.Observable();
  16570. /**
  16571. * Observable event triggered each time an keyboard event is received from the hosting window
  16572. */
  16573. this.onKeyboardObservable = new BABYLON.Observable();
  16574. // Coordinate system
  16575. /**
  16576. * use right-handed coordinate system on this scene.
  16577. * @type {boolean}
  16578. */
  16579. this._useRightHandedSystem = false;
  16580. // Fog
  16581. this._fogEnabled = true;
  16582. this._fogMode = Scene.FOGMODE_NONE;
  16583. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16584. this.fogDensity = 0.1;
  16585. this.fogStart = 0;
  16586. this.fogEnd = 1000.0;
  16587. // Lights
  16588. /**
  16589. * is shadow enabled on this scene.
  16590. * @type {boolean}
  16591. */
  16592. this._shadowsEnabled = true;
  16593. /**
  16594. * is light enabled on this scene.
  16595. * @type {boolean}
  16596. */
  16597. this._lightsEnabled = true;
  16598. /**
  16599. * All of the lights added to this scene.
  16600. * @see BABYLON.Light
  16601. * @type {BABYLON.Light[]}
  16602. */
  16603. this.lights = new Array();
  16604. // Cameras
  16605. /** All of the cameras added to this scene. */
  16606. this.cameras = new Array();
  16607. /** All of the active cameras added to this scene. */
  16608. this.activeCameras = new Array();
  16609. // Meshes
  16610. /**
  16611. * All of the (abstract) meshes added to this scene.
  16612. * @see BABYLON.AbstractMesh
  16613. * @type {BABYLON.AbstractMesh[]}
  16614. */
  16615. this.meshes = new Array();
  16616. // Geometries
  16617. this._geometries = new Array();
  16618. this.materials = new Array();
  16619. this.multiMaterials = new Array();
  16620. // Textures
  16621. this._texturesEnabled = true;
  16622. this.textures = new Array();
  16623. // Particles
  16624. this.particlesEnabled = true;
  16625. this.particleSystems = new Array();
  16626. // Sprites
  16627. this.spritesEnabled = true;
  16628. this.spriteManagers = new Array();
  16629. // Layers
  16630. this.layers = new Array();
  16631. this.highlightLayers = new Array();
  16632. // Skeletons
  16633. this._skeletonsEnabled = true;
  16634. this.skeletons = new Array();
  16635. // Morph targets
  16636. this.morphTargetManagers = new Array();
  16637. // Lens flares
  16638. this.lensFlaresEnabled = true;
  16639. this.lensFlareSystems = new Array();
  16640. // Collisions
  16641. this.collisionsEnabled = true;
  16642. /** Defines the gravity applied to this scene */
  16643. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16644. // Postprocesses
  16645. this.postProcesses = new Array();
  16646. this.postProcessesEnabled = true;
  16647. // Customs render targets
  16648. this.renderTargetsEnabled = true;
  16649. this.dumpNextRenderTargets = false;
  16650. this.customRenderTargets = new Array();
  16651. // Imported meshes
  16652. this.importedMeshesFiles = new Array();
  16653. // Probes
  16654. this.probesEnabled = true;
  16655. this.reflectionProbes = new Array();
  16656. this._actionManagers = new Array();
  16657. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16658. // Procedural textures
  16659. this.proceduralTexturesEnabled = true;
  16660. this._proceduralTextures = new Array();
  16661. this.soundTracks = new Array();
  16662. this._audioEnabled = true;
  16663. this._headphone = false;
  16664. // Performance counters
  16665. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16666. this._totalLightsCounter = new BABYLON.PerfCounter();
  16667. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16668. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16669. this._totalVertices = new BABYLON.PerfCounter();
  16670. this._activeIndices = new BABYLON.PerfCounter();
  16671. this._activeParticles = new BABYLON.PerfCounter();
  16672. this._interFrameDuration = new BABYLON.PerfCounter();
  16673. this._lastFrameDuration = new BABYLON.PerfCounter();
  16674. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16675. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16676. this._particlesDuration = new BABYLON.PerfCounter();
  16677. this._renderDuration = new BABYLON.PerfCounter();
  16678. this._spritesDuration = new BABYLON.PerfCounter();
  16679. this._activeBones = new BABYLON.PerfCounter();
  16680. this._animationTime = 0;
  16681. this.animationTimeScale = 1;
  16682. this._renderId = 0;
  16683. this._executeWhenReadyTimeoutId = -1;
  16684. this._intermediateRendering = false;
  16685. this._viewUpdateFlag = -1;
  16686. this._projectionUpdateFlag = -1;
  16687. this._alternateViewUpdateFlag = -1;
  16688. this._alternateProjectionUpdateFlag = -1;
  16689. this._toBeDisposed = new BABYLON.SmartArray(256);
  16690. this._pendingData = []; //ANY
  16691. this._activeMeshes = new BABYLON.SmartArray(256);
  16692. this._processedMaterials = new BABYLON.SmartArray(256);
  16693. this._renderTargets = new BABYLON.SmartArray(256);
  16694. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16695. this._activeSkeletons = new BABYLON.SmartArray(32);
  16696. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16697. this._activeAnimatables = new Array();
  16698. this._transformMatrix = BABYLON.Matrix.Zero();
  16699. this._useAlternateCameraConfiguration = false;
  16700. this._alternateRendering = false;
  16701. this.requireLightSorting = false;
  16702. this._uniqueIdCounter = 0;
  16703. this._activeMeshesFrozen = false;
  16704. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16705. this._engine.scenes.push(this);
  16706. this._uid = null;
  16707. this._renderingManager = new BABYLON.RenderingManager(this);
  16708. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16709. if (BABYLON.OutlineRenderer) {
  16710. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16711. }
  16712. this.attachControl();
  16713. if (BABYLON.SoundTrack) {
  16714. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16715. }
  16716. //simplification queue
  16717. if (BABYLON.SimplificationQueue) {
  16718. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16719. }
  16720. //collision coordinator initialization. For now legacy per default.
  16721. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16722. // Uniform Buffer
  16723. this._createUbo();
  16724. // Default Image processing definition.
  16725. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16726. }
  16727. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16728. /** The fog is deactivated */
  16729. get: function () {
  16730. return Scene._FOGMODE_NONE;
  16731. },
  16732. enumerable: true,
  16733. configurable: true
  16734. });
  16735. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16736. /** The fog density is following an exponential function */
  16737. get: function () {
  16738. return Scene._FOGMODE_EXP;
  16739. },
  16740. enumerable: true,
  16741. configurable: true
  16742. });
  16743. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16744. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16745. get: function () {
  16746. return Scene._FOGMODE_EXP2;
  16747. },
  16748. enumerable: true,
  16749. configurable: true
  16750. });
  16751. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16752. /** The fog density is following a linear function. */
  16753. get: function () {
  16754. return Scene._FOGMODE_LINEAR;
  16755. },
  16756. enumerable: true,
  16757. configurable: true
  16758. });
  16759. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16760. /**
  16761. * Texture used in all pbr material as the reflection texture.
  16762. * As in the majority of the scene they are the same (exception for multi room and so on),
  16763. * this is easier to reference from here than from all the materials.
  16764. */
  16765. get: function () {
  16766. return this._environmentTexture;
  16767. },
  16768. /**
  16769. * Texture used in all pbr material as the reflection texture.
  16770. * As in the majority of the scene they are the same (exception for multi room and so on),
  16771. * this is easier to set here than in all the materials.
  16772. */
  16773. set: function (value) {
  16774. this._environmentTexture = value;
  16775. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16776. },
  16777. enumerable: true,
  16778. configurable: true
  16779. });
  16780. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16781. /**
  16782. * Default image processing configuration used either in the rendering
  16783. * Forward main pass or through the imageProcessingPostProcess if present.
  16784. * As in the majority of the scene they are the same (exception for multi camera),
  16785. * this is easier to reference from here than from all the materials and post process.
  16786. *
  16787. * No setter as we it is a shared configuration, you can set the values instead.
  16788. */
  16789. get: function () {
  16790. return this._imageProcessingConfiguration;
  16791. },
  16792. enumerable: true,
  16793. configurable: true
  16794. });
  16795. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16796. get: function () {
  16797. return this._forcePointsCloud;
  16798. },
  16799. set: function (value) {
  16800. if (this._forcePointsCloud === value) {
  16801. return;
  16802. }
  16803. this._forcePointsCloud = value;
  16804. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16805. },
  16806. enumerable: true,
  16807. configurable: true
  16808. });
  16809. Object.defineProperty(Scene.prototype, "onDispose", {
  16810. /** A function to be executed when this scene is disposed. */
  16811. set: function (callback) {
  16812. if (this._onDisposeObserver) {
  16813. this.onDisposeObservable.remove(this._onDisposeObserver);
  16814. }
  16815. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16816. },
  16817. enumerable: true,
  16818. configurable: true
  16819. });
  16820. Object.defineProperty(Scene.prototype, "beforeRender", {
  16821. /** A function to be executed before rendering this scene */
  16822. set: function (callback) {
  16823. if (this._onBeforeRenderObserver) {
  16824. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16825. }
  16826. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16827. },
  16828. enumerable: true,
  16829. configurable: true
  16830. });
  16831. Object.defineProperty(Scene.prototype, "afterRender", {
  16832. /** A function to be executed after rendering this scene */
  16833. set: function (callback) {
  16834. if (this._onAfterRenderObserver) {
  16835. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16836. }
  16837. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16838. },
  16839. enumerable: true,
  16840. configurable: true
  16841. });
  16842. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16843. set: function (callback) {
  16844. if (this._onBeforeCameraRenderObserver) {
  16845. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16846. }
  16847. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16848. },
  16849. enumerable: true,
  16850. configurable: true
  16851. });
  16852. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16853. set: function (callback) {
  16854. if (this._onAfterCameraRenderObserver) {
  16855. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16856. }
  16857. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16858. },
  16859. enumerable: true,
  16860. configurable: true
  16861. });
  16862. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16863. get: function () {
  16864. if (!this._gamepadManager) {
  16865. this._gamepadManager = new BABYLON.GamepadManager();
  16866. }
  16867. return this._gamepadManager;
  16868. },
  16869. enumerable: true,
  16870. configurable: true
  16871. });
  16872. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16873. get: function () {
  16874. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16875. },
  16876. enumerable: true,
  16877. configurable: true
  16878. });
  16879. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16880. get: function () {
  16881. return this._useRightHandedSystem;
  16882. },
  16883. set: function (value) {
  16884. if (this._useRightHandedSystem === value) {
  16885. return;
  16886. }
  16887. this._useRightHandedSystem = value;
  16888. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16889. },
  16890. enumerable: true,
  16891. configurable: true
  16892. });
  16893. Scene.prototype.setStepId = function (newStepId) {
  16894. this._currentStepId = newStepId;
  16895. };
  16896. ;
  16897. Scene.prototype.getStepId = function () {
  16898. return this._currentStepId;
  16899. };
  16900. ;
  16901. Scene.prototype.getInternalStep = function () {
  16902. return this._currentInternalStep;
  16903. };
  16904. ;
  16905. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16906. get: function () {
  16907. return this._fogEnabled;
  16908. },
  16909. /**
  16910. * is fog enabled on this scene.
  16911. */
  16912. set: function (value) {
  16913. if (this._fogEnabled === value) {
  16914. return;
  16915. }
  16916. this._fogEnabled = value;
  16917. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16918. },
  16919. enumerable: true,
  16920. configurable: true
  16921. });
  16922. Object.defineProperty(Scene.prototype, "fogMode", {
  16923. get: function () {
  16924. return this._fogMode;
  16925. },
  16926. set: function (value) {
  16927. if (this._fogMode === value) {
  16928. return;
  16929. }
  16930. this._fogMode = value;
  16931. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16932. },
  16933. enumerable: true,
  16934. configurable: true
  16935. });
  16936. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16937. get: function () {
  16938. return this._shadowsEnabled;
  16939. },
  16940. set: function (value) {
  16941. if (this._shadowsEnabled === value) {
  16942. return;
  16943. }
  16944. this._shadowsEnabled = value;
  16945. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16946. },
  16947. enumerable: true,
  16948. configurable: true
  16949. });
  16950. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16951. get: function () {
  16952. return this._lightsEnabled;
  16953. },
  16954. set: function (value) {
  16955. if (this._lightsEnabled === value) {
  16956. return;
  16957. }
  16958. this._lightsEnabled = value;
  16959. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16960. },
  16961. enumerable: true,
  16962. configurable: true
  16963. });
  16964. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16965. /** The default material used on meshes when no material is affected */
  16966. get: function () {
  16967. if (!this._defaultMaterial) {
  16968. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16969. }
  16970. return this._defaultMaterial;
  16971. },
  16972. /** The default material used on meshes when no material is affected */
  16973. set: function (value) {
  16974. this._defaultMaterial = value;
  16975. },
  16976. enumerable: true,
  16977. configurable: true
  16978. });
  16979. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16980. get: function () {
  16981. return this._texturesEnabled;
  16982. },
  16983. set: function (value) {
  16984. if (this._texturesEnabled === value) {
  16985. return;
  16986. }
  16987. this._texturesEnabled = value;
  16988. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16989. },
  16990. enumerable: true,
  16991. configurable: true
  16992. });
  16993. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16994. get: function () {
  16995. return this._skeletonsEnabled;
  16996. },
  16997. set: function (value) {
  16998. if (this._skeletonsEnabled === value) {
  16999. return;
  17000. }
  17001. this._skeletonsEnabled = value;
  17002. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17003. },
  17004. enumerable: true,
  17005. configurable: true
  17006. });
  17007. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17008. get: function () {
  17009. if (!this._postProcessRenderPipelineManager) {
  17010. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17011. }
  17012. return this._postProcessRenderPipelineManager;
  17013. },
  17014. enumerable: true,
  17015. configurable: true
  17016. });
  17017. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17018. get: function () {
  17019. return this._alternateRendering;
  17020. },
  17021. enumerable: true,
  17022. configurable: true
  17023. });
  17024. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17025. get: function () {
  17026. return this._frustumPlanes;
  17027. },
  17028. enumerable: true,
  17029. configurable: true
  17030. });
  17031. Object.defineProperty(Scene.prototype, "debugLayer", {
  17032. // Properties
  17033. get: function () {
  17034. if (!this._debugLayer) {
  17035. this._debugLayer = new BABYLON.DebugLayer(this);
  17036. }
  17037. return this._debugLayer;
  17038. },
  17039. enumerable: true,
  17040. configurable: true
  17041. });
  17042. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17043. get: function () {
  17044. return this._workerCollisions;
  17045. },
  17046. set: function (enabled) {
  17047. if (!BABYLON.CollisionCoordinatorLegacy) {
  17048. return;
  17049. }
  17050. enabled = (enabled && !!Worker);
  17051. this._workerCollisions = enabled;
  17052. if (this.collisionCoordinator) {
  17053. this.collisionCoordinator.destroy();
  17054. }
  17055. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17056. this.collisionCoordinator.init(this);
  17057. },
  17058. enumerable: true,
  17059. configurable: true
  17060. });
  17061. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17062. get: function () {
  17063. return this._selectionOctree;
  17064. },
  17065. enumerable: true,
  17066. configurable: true
  17067. });
  17068. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17069. /**
  17070. * The mesh that is currently under the pointer.
  17071. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17072. */
  17073. get: function () {
  17074. return this._pointerOverMesh;
  17075. },
  17076. enumerable: true,
  17077. configurable: true
  17078. });
  17079. Object.defineProperty(Scene.prototype, "pointerX", {
  17080. /**
  17081. * Current on-screen X position of the pointer
  17082. * @return {number} X position of the pointer
  17083. */
  17084. get: function () {
  17085. return this._pointerX;
  17086. },
  17087. enumerable: true,
  17088. configurable: true
  17089. });
  17090. Object.defineProperty(Scene.prototype, "pointerY", {
  17091. /**
  17092. * Current on-screen Y position of the pointer
  17093. * @return {number} Y position of the pointer
  17094. */
  17095. get: function () {
  17096. return this._pointerY;
  17097. },
  17098. enumerable: true,
  17099. configurable: true
  17100. });
  17101. Scene.prototype.getCachedMaterial = function () {
  17102. return this._cachedMaterial;
  17103. };
  17104. Scene.prototype.getCachedEffect = function () {
  17105. return this._cachedEffect;
  17106. };
  17107. Scene.prototype.getCachedVisibility = function () {
  17108. return this._cachedVisibility;
  17109. };
  17110. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17111. if (visibility === void 0) { visibility = 1; }
  17112. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17113. };
  17114. Scene.prototype.getBoundingBoxRenderer = function () {
  17115. if (!this._boundingBoxRenderer) {
  17116. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17117. }
  17118. return this._boundingBoxRenderer;
  17119. };
  17120. Scene.prototype.getOutlineRenderer = function () {
  17121. return this._outlineRenderer;
  17122. };
  17123. Scene.prototype.getEngine = function () {
  17124. return this._engine;
  17125. };
  17126. Scene.prototype.getTotalVertices = function () {
  17127. return this._totalVertices.current;
  17128. };
  17129. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17130. get: function () {
  17131. return this._totalVertices;
  17132. },
  17133. enumerable: true,
  17134. configurable: true
  17135. });
  17136. Scene.prototype.getActiveIndices = function () {
  17137. return this._activeIndices.current;
  17138. };
  17139. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17140. get: function () {
  17141. return this._activeIndices;
  17142. },
  17143. enumerable: true,
  17144. configurable: true
  17145. });
  17146. Scene.prototype.getActiveParticles = function () {
  17147. return this._activeParticles.current;
  17148. };
  17149. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17150. get: function () {
  17151. return this._activeParticles;
  17152. },
  17153. enumerable: true,
  17154. configurable: true
  17155. });
  17156. Scene.prototype.getActiveBones = function () {
  17157. return this._activeBones.current;
  17158. };
  17159. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17160. get: function () {
  17161. return this._activeBones;
  17162. },
  17163. enumerable: true,
  17164. configurable: true
  17165. });
  17166. // Stats
  17167. Scene.prototype.getInterFramePerfCounter = function () {
  17168. return this._interFrameDuration.current;
  17169. };
  17170. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17171. get: function () {
  17172. return this._interFrameDuration;
  17173. },
  17174. enumerable: true,
  17175. configurable: true
  17176. });
  17177. Scene.prototype.getLastFrameDuration = function () {
  17178. return this._lastFrameDuration.current;
  17179. };
  17180. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17181. get: function () {
  17182. return this._lastFrameDuration;
  17183. },
  17184. enumerable: true,
  17185. configurable: true
  17186. });
  17187. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17188. return this._evaluateActiveMeshesDuration.current;
  17189. };
  17190. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17191. get: function () {
  17192. return this._evaluateActiveMeshesDuration;
  17193. },
  17194. enumerable: true,
  17195. configurable: true
  17196. });
  17197. Scene.prototype.getActiveMeshes = function () {
  17198. return this._activeMeshes;
  17199. };
  17200. Scene.prototype.getRenderTargetsDuration = function () {
  17201. return this._renderTargetsDuration.current;
  17202. };
  17203. Scene.prototype.getRenderDuration = function () {
  17204. return this._renderDuration.current;
  17205. };
  17206. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17207. get: function () {
  17208. return this._renderDuration;
  17209. },
  17210. enumerable: true,
  17211. configurable: true
  17212. });
  17213. Scene.prototype.getParticlesDuration = function () {
  17214. return this._particlesDuration.current;
  17215. };
  17216. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17217. get: function () {
  17218. return this._particlesDuration;
  17219. },
  17220. enumerable: true,
  17221. configurable: true
  17222. });
  17223. Scene.prototype.getSpritesDuration = function () {
  17224. return this._spritesDuration.current;
  17225. };
  17226. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17227. get: function () {
  17228. return this._spritesDuration;
  17229. },
  17230. enumerable: true,
  17231. configurable: true
  17232. });
  17233. Scene.prototype.getAnimationRatio = function () {
  17234. return this._animationRatio;
  17235. };
  17236. Scene.prototype.getRenderId = function () {
  17237. return this._renderId;
  17238. };
  17239. Scene.prototype.incrementRenderId = function () {
  17240. this._renderId++;
  17241. };
  17242. Scene.prototype._updatePointerPosition = function (evt) {
  17243. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17244. this._pointerX = evt.clientX - canvasRect.left;
  17245. this._pointerY = evt.clientY - canvasRect.top;
  17246. this._unTranslatedPointerX = this._pointerX;
  17247. this._unTranslatedPointerY = this._pointerY;
  17248. };
  17249. Scene.prototype._createUbo = function () {
  17250. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17251. this._sceneUbo.addUniform("viewProjection", 16);
  17252. this._sceneUbo.addUniform("view", 16);
  17253. };
  17254. Scene.prototype._createAlternateUbo = function () {
  17255. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17256. this._alternateSceneUbo.addUniform("viewProjection", 16);
  17257. this._alternateSceneUbo.addUniform("view", 16);
  17258. };
  17259. // Pointers handling
  17260. /**
  17261. * Use this method to simulate a pointer move on a mesh
  17262. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17263. */
  17264. Scene.prototype.simulatePointerMove = function (pickResult) {
  17265. var evt = new PointerEvent("pointermove");
  17266. return this._processPointerMove(pickResult, evt);
  17267. };
  17268. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17269. var canvas = this._engine.getRenderingCanvas();
  17270. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17271. this.setPointerOverSprite(null);
  17272. this.setPointerOverMesh(pickResult.pickedMesh);
  17273. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17274. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17275. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17276. }
  17277. else {
  17278. canvas.style.cursor = this.hoverCursor;
  17279. }
  17280. }
  17281. else {
  17282. canvas.style.cursor = this.defaultCursor;
  17283. }
  17284. }
  17285. else {
  17286. this.setPointerOverMesh(null);
  17287. // Sprites
  17288. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17289. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17290. this.setPointerOverSprite(pickResult.pickedSprite);
  17291. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17292. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17293. }
  17294. else {
  17295. canvas.style.cursor = this.hoverCursor;
  17296. }
  17297. }
  17298. else {
  17299. this.setPointerOverSprite(null);
  17300. // Restore pointer
  17301. canvas.style.cursor = this.defaultCursor;
  17302. }
  17303. }
  17304. if (this.onPointerMove) {
  17305. this.onPointerMove(evt, pickResult);
  17306. }
  17307. if (this.onPointerObservable.hasObservers()) {
  17308. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17309. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17310. this.onPointerObservable.notifyObservers(pi, type);
  17311. }
  17312. return this;
  17313. };
  17314. /**
  17315. * Use this method to simulate a pointer down on a mesh
  17316. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17317. */
  17318. Scene.prototype.simulatePointerDown = function (pickResult) {
  17319. var evt = new PointerEvent("pointerdown");
  17320. return this._processPointerDown(pickResult, evt);
  17321. };
  17322. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17323. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17324. this._pickedDownMesh = pickResult.pickedMesh;
  17325. var actionManager = pickResult.pickedMesh.actionManager;
  17326. if (actionManager) {
  17327. if (actionManager.hasPickTriggers) {
  17328. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17329. switch (evt.button) {
  17330. case 0:
  17331. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17332. break;
  17333. case 1:
  17334. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17335. break;
  17336. case 2:
  17337. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17338. break;
  17339. }
  17340. }
  17341. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17342. window.setTimeout((function () {
  17343. var _this = this;
  17344. 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);
  17345. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17346. if (this._isButtonPressed &&
  17347. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17348. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17349. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17350. this._startingPointerTime = 0;
  17351. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17352. }
  17353. }
  17354. }).bind(this), Scene.LongPressDelay);
  17355. }
  17356. }
  17357. }
  17358. if (this.onPointerDown) {
  17359. this.onPointerDown(evt, pickResult);
  17360. }
  17361. if (this.onPointerObservable.hasObservers()) {
  17362. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17363. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17364. this.onPointerObservable.notifyObservers(pi, type);
  17365. }
  17366. return this;
  17367. };
  17368. /**
  17369. * Use this method to simulate a pointer up on a mesh
  17370. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17371. */
  17372. Scene.prototype.simulatePointerUp = function (pickResult) {
  17373. var evt = new PointerEvent("pointerup");
  17374. var clickInfo = new ClickInfo();
  17375. clickInfo.singleClick = true;
  17376. return this._processPointerUp(pickResult, evt, clickInfo);
  17377. };
  17378. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17379. if (pickResult && pickResult && pickResult.pickedMesh) {
  17380. this._pickedUpMesh = pickResult.pickedMesh;
  17381. if (this._pickedDownMesh === this._pickedUpMesh) {
  17382. if (this.onPointerPick) {
  17383. this.onPointerPick(evt, pickResult);
  17384. }
  17385. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17386. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17387. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17388. this.onPointerObservable.notifyObservers(pi, type);
  17389. }
  17390. }
  17391. if (pickResult.pickedMesh.actionManager) {
  17392. if (clickInfo.ignore) {
  17393. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17394. }
  17395. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17396. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17397. }
  17398. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17399. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17400. }
  17401. }
  17402. }
  17403. if (this._pickedDownMesh &&
  17404. this._pickedDownMesh.actionManager &&
  17405. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17406. this._pickedDownMesh !== this._pickedUpMesh) {
  17407. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17408. }
  17409. if (this.onPointerUp) {
  17410. this.onPointerUp(evt, pickResult);
  17411. }
  17412. if (this.onPointerObservable.hasObservers()) {
  17413. if (!clickInfo.ignore) {
  17414. if (!clickInfo.hasSwiped) {
  17415. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17416. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17417. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17418. this.onPointerObservable.notifyObservers(pi, type);
  17419. }
  17420. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17421. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17422. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17423. this.onPointerObservable.notifyObservers(pi, type);
  17424. }
  17425. }
  17426. }
  17427. else {
  17428. var type = BABYLON.PointerEventTypes.POINTERUP;
  17429. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17430. this.onPointerObservable.notifyObservers(pi, type);
  17431. }
  17432. }
  17433. return this;
  17434. };
  17435. /**
  17436. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17437. * @param attachUp defines if you want to attach events to pointerup
  17438. * @param attachDown defines if you want to attach events to pointerdown
  17439. * @param attachMove defines if you want to attach events to pointermove
  17440. */
  17441. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17442. var _this = this;
  17443. if (attachUp === void 0) { attachUp = true; }
  17444. if (attachDown === void 0) { attachDown = true; }
  17445. if (attachMove === void 0) { attachMove = true; }
  17446. this._initActionManager = function (act, clickInfo) {
  17447. if (!_this._meshPickProceed) {
  17448. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17449. _this._currentPickResult = pickResult;
  17450. if (pickResult) {
  17451. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17452. }
  17453. _this._meshPickProceed = true;
  17454. }
  17455. return act;
  17456. };
  17457. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17458. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17459. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17460. btn !== _this._previousButtonPressed) {
  17461. _this._doubleClickOccured = false;
  17462. clickInfo.singleClick = true;
  17463. clickInfo.ignore = false;
  17464. cb(clickInfo, _this._currentPickResult);
  17465. }
  17466. };
  17467. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17468. var clickInfo = new ClickInfo();
  17469. _this._currentPickResult = null;
  17470. var act;
  17471. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17472. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17473. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17474. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17475. act = _this._initActionManager(act, clickInfo);
  17476. if (act)
  17477. checkPicking = act.hasPickTriggers;
  17478. }
  17479. if (checkPicking) {
  17480. var btn = evt.button;
  17481. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17482. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17483. if (!clickInfo.hasSwiped) {
  17484. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17485. if (!checkSingleClickImmediately) {
  17486. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17487. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17488. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17489. act = _this._initActionManager(act, clickInfo);
  17490. if (act)
  17491. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17492. }
  17493. }
  17494. if (checkSingleClickImmediately) {
  17495. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17496. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17497. btn !== _this._previousButtonPressed) {
  17498. clickInfo.singleClick = true;
  17499. cb(clickInfo, _this._currentPickResult);
  17500. }
  17501. }
  17502. else {
  17503. // wait that no double click has been raised during the double click delay
  17504. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17505. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17506. }
  17507. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17508. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17509. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17510. act = _this._initActionManager(act, clickInfo);
  17511. if (act)
  17512. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17513. }
  17514. if (checkDoubleClick) {
  17515. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17516. if (btn === _this._previousButtonPressed &&
  17517. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17518. !_this._doubleClickOccured) {
  17519. // pointer has not moved for 2 clicks, it's a double click
  17520. if (!clickInfo.hasSwiped &&
  17521. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17522. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17523. _this._previousStartingPointerTime = 0;
  17524. _this._doubleClickOccured = true;
  17525. clickInfo.doubleClick = true;
  17526. clickInfo.ignore = false;
  17527. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17528. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17529. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17530. cb(clickInfo, _this._currentPickResult);
  17531. }
  17532. else {
  17533. _this._doubleClickOccured = false;
  17534. _this._previousStartingPointerTime = _this._startingPointerTime;
  17535. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17536. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17537. _this._previousButtonPressed = btn;
  17538. _this._previousHasSwiped = clickInfo.hasSwiped;
  17539. if (Scene.ExclusiveDoubleClickMode) {
  17540. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17541. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17542. }
  17543. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17544. cb(clickInfo, _this._previousPickResult);
  17545. }
  17546. else {
  17547. cb(clickInfo, _this._currentPickResult);
  17548. }
  17549. }
  17550. }
  17551. else {
  17552. _this._doubleClickOccured = false;
  17553. _this._previousStartingPointerTime = _this._startingPointerTime;
  17554. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17555. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17556. _this._previousButtonPressed = btn;
  17557. _this._previousHasSwiped = clickInfo.hasSwiped;
  17558. }
  17559. }
  17560. }
  17561. }
  17562. clickInfo.ignore = true;
  17563. cb(clickInfo, _this._currentPickResult);
  17564. };
  17565. this._spritePredicate = function (sprite) {
  17566. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17567. };
  17568. this._onPointerMove = function (evt) {
  17569. _this._updatePointerPosition(evt);
  17570. // PreObservable support
  17571. if (_this.onPrePointerObservable.hasObservers()) {
  17572. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17573. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17574. _this.onPrePointerObservable.notifyObservers(pi, type);
  17575. if (pi.skipOnPointerObservable) {
  17576. return;
  17577. }
  17578. }
  17579. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17580. return;
  17581. }
  17582. if (!_this.pointerMovePredicate) {
  17583. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17584. }
  17585. // Meshes
  17586. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17587. _this._processPointerMove(pickResult, evt);
  17588. };
  17589. this._onPointerDown = function (evt) {
  17590. _this._isButtonPressed = true;
  17591. _this._pickedDownMesh = null;
  17592. _this._meshPickProceed = false;
  17593. _this._updatePointerPosition(evt);
  17594. // PreObservable support
  17595. if (_this.onPrePointerObservable.hasObservers()) {
  17596. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17597. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17598. _this.onPrePointerObservable.notifyObservers(pi, type);
  17599. if (pi.skipOnPointerObservable) {
  17600. return;
  17601. }
  17602. }
  17603. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17604. return;
  17605. }
  17606. _this._startingPointerPosition.x = _this._pointerX;
  17607. _this._startingPointerPosition.y = _this._pointerY;
  17608. _this._startingPointerTime = new Date().getTime();
  17609. if (!_this.pointerDownPredicate) {
  17610. _this.pointerDownPredicate = function (mesh) {
  17611. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17612. };
  17613. }
  17614. // Meshes
  17615. _this._pickedDownMesh = null;
  17616. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17617. _this._processPointerDown(pickResult, evt);
  17618. // Sprites
  17619. _this._pickedDownSprite = null;
  17620. if (_this.spriteManagers.length > 0) {
  17621. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  17622. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17623. if (pickResult.pickedSprite.actionManager) {
  17624. _this._pickedDownSprite = pickResult.pickedSprite;
  17625. switch (evt.button) {
  17626. case 0:
  17627. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17628. break;
  17629. case 1:
  17630. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17631. break;
  17632. case 2:
  17633. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17634. break;
  17635. }
  17636. if (pickResult.pickedSprite.actionManager) {
  17637. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17638. }
  17639. }
  17640. }
  17641. }
  17642. };
  17643. this._onPointerUp = function (evt) {
  17644. _this._isButtonPressed = false;
  17645. _this._pickedUpMesh = null;
  17646. _this._meshPickProceed = false;
  17647. _this._updatePointerPosition(evt);
  17648. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17649. // PreObservable support
  17650. if (this.onPrePointerObservable.hasObservers()) {
  17651. if (!clickInfo.ignore) {
  17652. if (!clickInfo.hasSwiped) {
  17653. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17654. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17655. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17656. this.onPrePointerObservable.notifyObservers(pi, type);
  17657. if (pi.skipOnPointerObservable) {
  17658. return;
  17659. }
  17660. }
  17661. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17662. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17663. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17664. this.onPrePointerObservable.notifyObservers(pi, type);
  17665. if (pi.skipOnPointerObservable) {
  17666. return;
  17667. }
  17668. }
  17669. }
  17670. }
  17671. else {
  17672. var type = BABYLON.PointerEventTypes.POINTERUP;
  17673. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17674. this.onPrePointerObservable.notifyObservers(pi, type);
  17675. if (pi.skipOnPointerObservable) {
  17676. return;
  17677. }
  17678. }
  17679. }
  17680. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17681. return;
  17682. }
  17683. if (!this.pointerUpPredicate) {
  17684. this.pointerUpPredicate = function (mesh) {
  17685. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17686. };
  17687. }
  17688. // Meshes
  17689. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17690. this._initActionManager(null, clickInfo);
  17691. }
  17692. if (!pickResult) {
  17693. pickResult = this._currentPickResult;
  17694. }
  17695. this._processPointerUp(pickResult, evt, clickInfo);
  17696. // Sprites
  17697. if (this.spriteManagers.length > 0) {
  17698. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17699. if (pickResult.hit && pickResult.pickedSprite) {
  17700. if (pickResult.pickedSprite.actionManager) {
  17701. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17702. if (pickResult.pickedSprite.actionManager) {
  17703. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17704. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17705. }
  17706. }
  17707. }
  17708. }
  17709. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17710. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17711. }
  17712. }
  17713. this._previousPickResult = this._currentPickResult;
  17714. }).bind(_this));
  17715. };
  17716. this._onKeyDown = function (evt) {
  17717. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17718. if (_this.onPreKeyboardObservable.hasObservers()) {
  17719. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17720. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17721. if (pi.skipOnPointerObservable) {
  17722. return;
  17723. }
  17724. }
  17725. if (_this.onKeyboardObservable.hasObservers()) {
  17726. var pi = new BABYLON.KeyboardInfo(type, evt);
  17727. _this.onKeyboardObservable.notifyObservers(pi, type);
  17728. }
  17729. if (_this.actionManager) {
  17730. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17731. }
  17732. };
  17733. this._onKeyUp = function (evt) {
  17734. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17735. if (_this.onPreKeyboardObservable.hasObservers()) {
  17736. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17737. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17738. if (pi.skipOnPointerObservable) {
  17739. return;
  17740. }
  17741. }
  17742. if (_this.onKeyboardObservable.hasObservers()) {
  17743. var pi = new BABYLON.KeyboardInfo(type, evt);
  17744. _this.onKeyboardObservable.notifyObservers(pi, type);
  17745. }
  17746. if (_this.actionManager) {
  17747. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17748. }
  17749. };
  17750. var engine = this.getEngine();
  17751. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17752. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17753. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17754. });
  17755. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17756. canvas.removeEventListener("keydown", _this._onKeyDown);
  17757. canvas.removeEventListener("keyup", _this._onKeyUp);
  17758. });
  17759. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17760. var canvas = this._engine.getRenderingCanvas();
  17761. if (attachMove) {
  17762. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17763. // Wheel
  17764. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17765. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17766. }
  17767. if (attachDown) {
  17768. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17769. }
  17770. if (attachUp) {
  17771. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17772. }
  17773. canvas.tabIndex = 1;
  17774. };
  17775. Scene.prototype.detachControl = function () {
  17776. var engine = this.getEngine();
  17777. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17778. var canvas = engine.getRenderingCanvas();
  17779. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17780. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17781. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17782. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17783. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17784. // Wheel
  17785. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17786. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17787. // Keyboard
  17788. canvas.removeEventListener("keydown", this._onKeyDown);
  17789. canvas.removeEventListener("keyup", this._onKeyUp);
  17790. // Observables
  17791. this.onKeyboardObservable.clear();
  17792. this.onPreKeyboardObservable.clear();
  17793. this.onPointerObservable.clear();
  17794. this.onPrePointerObservable.clear();
  17795. };
  17796. // Ready
  17797. Scene.prototype.isReady = function () {
  17798. if (this._pendingData.length > 0) {
  17799. return false;
  17800. }
  17801. var index;
  17802. // Geometries
  17803. for (index = 0; index < this._geometries.length; index++) {
  17804. var geometry = this._geometries[index];
  17805. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17806. return false;
  17807. }
  17808. }
  17809. // Meshes
  17810. for (index = 0; index < this.meshes.length; index++) {
  17811. var mesh = this.meshes[index];
  17812. if (!mesh.isEnabled()) {
  17813. continue;
  17814. }
  17815. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17816. continue;
  17817. }
  17818. if (!mesh.isReady()) {
  17819. return false;
  17820. }
  17821. var mat = mesh.material;
  17822. if (mat) {
  17823. if (!mat.isReady(mesh)) {
  17824. return false;
  17825. }
  17826. }
  17827. }
  17828. return true;
  17829. };
  17830. Scene.prototype.resetCachedMaterial = function () {
  17831. this._cachedMaterial = null;
  17832. this._cachedEffect = null;
  17833. this._cachedVisibility = null;
  17834. };
  17835. Scene.prototype.registerBeforeRender = function (func) {
  17836. this.onBeforeRenderObservable.add(func);
  17837. };
  17838. Scene.prototype.unregisterBeforeRender = function (func) {
  17839. this.onBeforeRenderObservable.removeCallback(func);
  17840. };
  17841. Scene.prototype.registerAfterRender = function (func) {
  17842. this.onAfterRenderObservable.add(func);
  17843. };
  17844. Scene.prototype.unregisterAfterRender = function (func) {
  17845. this.onAfterRenderObservable.removeCallback(func);
  17846. };
  17847. Scene.prototype._addPendingData = function (data) {
  17848. this._pendingData.push(data);
  17849. };
  17850. Scene.prototype._removePendingData = function (data) {
  17851. var index = this._pendingData.indexOf(data);
  17852. if (index !== -1) {
  17853. this._pendingData.splice(index, 1);
  17854. }
  17855. };
  17856. Scene.prototype.getWaitingItemsCount = function () {
  17857. return this._pendingData.length;
  17858. };
  17859. /**
  17860. * Registers a function to be executed when the scene is ready.
  17861. * @param {Function} func - the function to be executed.
  17862. */
  17863. Scene.prototype.executeWhenReady = function (func) {
  17864. var _this = this;
  17865. this.onReadyObservable.add(func);
  17866. if (this._executeWhenReadyTimeoutId !== -1) {
  17867. return;
  17868. }
  17869. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17870. _this._checkIsReady();
  17871. }, 150);
  17872. };
  17873. Scene.prototype._checkIsReady = function () {
  17874. var _this = this;
  17875. if (this.isReady()) {
  17876. this.onReadyObservable.notifyObservers(this);
  17877. this.onReadyObservable.clear();
  17878. this._executeWhenReadyTimeoutId = -1;
  17879. return;
  17880. }
  17881. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17882. _this._checkIsReady();
  17883. }, 150);
  17884. };
  17885. // Animations
  17886. /**
  17887. * Will start the animation sequence of a given target
  17888. * @param target - the target
  17889. * @param {number} from - from which frame should animation start
  17890. * @param {number} to - till which frame should animation run.
  17891. * @param {boolean} [loop] - should the animation loop
  17892. * @param {number} [speedRatio] - the speed in which to run the animation
  17893. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17894. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17895. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17896. * See BABYLON.Animatable
  17897. */
  17898. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17899. if (speedRatio === void 0) { speedRatio = 1.0; }
  17900. if (from > to && speedRatio > 0) {
  17901. speedRatio *= -1;
  17902. }
  17903. this.stopAnimation(target);
  17904. if (!animatable) {
  17905. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17906. }
  17907. // Local animations
  17908. if (target.animations) {
  17909. animatable.appendAnimations(target, target.animations);
  17910. }
  17911. // Children animations
  17912. if (target.getAnimatables) {
  17913. var animatables = target.getAnimatables();
  17914. for (var index = 0; index < animatables.length; index++) {
  17915. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17916. }
  17917. }
  17918. animatable.reset();
  17919. return animatable;
  17920. };
  17921. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17922. if (speedRatio === undefined) {
  17923. speedRatio = 1.0;
  17924. }
  17925. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17926. return animatable;
  17927. };
  17928. Scene.prototype.getAnimatableByTarget = function (target) {
  17929. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17930. if (this._activeAnimatables[index].target === target) {
  17931. return this._activeAnimatables[index];
  17932. }
  17933. }
  17934. return null;
  17935. };
  17936. Object.defineProperty(Scene.prototype, "Animatables", {
  17937. get: function () {
  17938. return this._activeAnimatables;
  17939. },
  17940. enumerable: true,
  17941. configurable: true
  17942. });
  17943. /**
  17944. * Will stop the animation of the given target
  17945. * @param target - the target
  17946. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17947. * @see beginAnimation
  17948. */
  17949. Scene.prototype.stopAnimation = function (target, animationName) {
  17950. var animatable = this.getAnimatableByTarget(target);
  17951. if (animatable) {
  17952. animatable.stop(animationName);
  17953. }
  17954. };
  17955. Scene.prototype._animate = function () {
  17956. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17957. return;
  17958. }
  17959. // Getting time
  17960. var now = BABYLON.Tools.Now;
  17961. if (!this._animationTimeLast) {
  17962. if (this._pendingData.length > 0) {
  17963. return;
  17964. }
  17965. this._animationTimeLast = now;
  17966. }
  17967. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17968. this._animationTime += deltaTime;
  17969. this._animationTimeLast = now;
  17970. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17971. this._activeAnimatables[index]._animate(this._animationTime);
  17972. }
  17973. };
  17974. // Matrix
  17975. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  17976. this._useAlternateCameraConfiguration = active;
  17977. };
  17978. Scene.prototype.getViewMatrix = function () {
  17979. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  17980. };
  17981. Scene.prototype.getProjectionMatrix = function () {
  17982. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  17983. };
  17984. Scene.prototype.getTransformMatrix = function () {
  17985. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  17986. };
  17987. Scene.prototype.setTransformMatrix = function (view, projection) {
  17988. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17989. return;
  17990. }
  17991. this._viewUpdateFlag = view.updateFlag;
  17992. this._projectionUpdateFlag = projection.updateFlag;
  17993. this._viewMatrix = view;
  17994. this._projectionMatrix = projection;
  17995. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17996. // Update frustum
  17997. if (!this._frustumPlanes) {
  17998. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17999. }
  18000. else {
  18001. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18002. }
  18003. if (this._sceneUbo.useUbo) {
  18004. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18005. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18006. this._sceneUbo.update();
  18007. }
  18008. };
  18009. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18010. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18011. return;
  18012. }
  18013. this._alternateViewUpdateFlag = view.updateFlag;
  18014. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18015. this._alternateViewMatrix = view;
  18016. this._alternateProjectionMatrix = projection;
  18017. if (!this._alternateTransformMatrix) {
  18018. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18019. }
  18020. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18021. if (!this._alternateSceneUbo) {
  18022. this._createAlternateUbo();
  18023. }
  18024. if (this._alternateSceneUbo.useUbo) {
  18025. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18026. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18027. this._alternateSceneUbo.update();
  18028. }
  18029. };
  18030. Scene.prototype.getSceneUniformBuffer = function () {
  18031. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18032. };
  18033. // Methods
  18034. Scene.prototype.getUniqueId = function () {
  18035. var result = this._uniqueIdCounter;
  18036. this._uniqueIdCounter++;
  18037. return result;
  18038. };
  18039. Scene.prototype.addMesh = function (newMesh) {
  18040. newMesh.uniqueId = this.getUniqueId();
  18041. var position = this.meshes.push(newMesh);
  18042. //notify the collision coordinator
  18043. if (this.collisionCoordinator) {
  18044. this.collisionCoordinator.onMeshAdded(newMesh);
  18045. }
  18046. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18047. };
  18048. Scene.prototype.removeMesh = function (toRemove) {
  18049. var index = this.meshes.indexOf(toRemove);
  18050. if (index !== -1) {
  18051. // Remove from the scene if mesh found
  18052. this.meshes.splice(index, 1);
  18053. }
  18054. //notify the collision coordinator
  18055. if (this.collisionCoordinator) {
  18056. this.collisionCoordinator.onMeshRemoved(toRemove);
  18057. }
  18058. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18059. return index;
  18060. };
  18061. Scene.prototype.removeSkeleton = function (toRemove) {
  18062. var index = this.skeletons.indexOf(toRemove);
  18063. if (index !== -1) {
  18064. // Remove from the scene if found
  18065. this.skeletons.splice(index, 1);
  18066. }
  18067. return index;
  18068. };
  18069. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18070. var index = this.morphTargetManagers.indexOf(toRemove);
  18071. if (index !== -1) {
  18072. // Remove from the scene if found
  18073. this.morphTargetManagers.splice(index, 1);
  18074. }
  18075. return index;
  18076. };
  18077. Scene.prototype.removeLight = function (toRemove) {
  18078. var index = this.lights.indexOf(toRemove);
  18079. if (index !== -1) {
  18080. // Remove from the scene if mesh found
  18081. this.lights.splice(index, 1);
  18082. this.sortLightsByPriority();
  18083. }
  18084. this.onLightRemovedObservable.notifyObservers(toRemove);
  18085. return index;
  18086. };
  18087. Scene.prototype.removeCamera = function (toRemove) {
  18088. var index = this.cameras.indexOf(toRemove);
  18089. if (index !== -1) {
  18090. // Remove from the scene if mesh found
  18091. this.cameras.splice(index, 1);
  18092. }
  18093. // Remove from activeCameras
  18094. var index2 = this.activeCameras.indexOf(toRemove);
  18095. if (index2 !== -1) {
  18096. // Remove from the scene if mesh found
  18097. this.activeCameras.splice(index2, 1);
  18098. }
  18099. // Reset the activeCamera
  18100. if (this.activeCamera === toRemove) {
  18101. if (this.cameras.length > 0) {
  18102. this.activeCamera = this.cameras[0];
  18103. }
  18104. else {
  18105. this.activeCamera = null;
  18106. }
  18107. }
  18108. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18109. return index;
  18110. };
  18111. Scene.prototype.addLight = function (newLight) {
  18112. newLight.uniqueId = this.getUniqueId();
  18113. this.lights.push(newLight);
  18114. this.sortLightsByPriority();
  18115. this.onNewLightAddedObservable.notifyObservers(newLight);
  18116. };
  18117. Scene.prototype.sortLightsByPriority = function () {
  18118. if (this.requireLightSorting) {
  18119. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18120. }
  18121. };
  18122. Scene.prototype.addCamera = function (newCamera) {
  18123. newCamera.uniqueId = this.getUniqueId();
  18124. var position = this.cameras.push(newCamera);
  18125. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18126. };
  18127. /**
  18128. * Switch active camera
  18129. * @param {Camera} newCamera - new active camera
  18130. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18131. */
  18132. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18133. if (attachControl === void 0) { attachControl = true; }
  18134. var canvas = this._engine.getRenderingCanvas();
  18135. this.activeCamera.detachControl(canvas);
  18136. this.activeCamera = newCamera;
  18137. if (attachControl) {
  18138. newCamera.attachControl(canvas);
  18139. }
  18140. };
  18141. /**
  18142. * sets the active camera of the scene using its ID
  18143. * @param {string} id - the camera's ID
  18144. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18145. * @see activeCamera
  18146. */
  18147. Scene.prototype.setActiveCameraByID = function (id) {
  18148. var camera = this.getCameraByID(id);
  18149. if (camera) {
  18150. this.activeCamera = camera;
  18151. return camera;
  18152. }
  18153. return null;
  18154. };
  18155. /**
  18156. * sets the active camera of the scene using its name
  18157. * @param {string} name - the camera's name
  18158. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18159. * @see activeCamera
  18160. */
  18161. Scene.prototype.setActiveCameraByName = function (name) {
  18162. var camera = this.getCameraByName(name);
  18163. if (camera) {
  18164. this.activeCamera = camera;
  18165. return camera;
  18166. }
  18167. return null;
  18168. };
  18169. /**
  18170. * get a material using its id
  18171. * @param {string} the material's ID
  18172. * @return {BABYLON.Material|null} the material or null if none found.
  18173. */
  18174. Scene.prototype.getMaterialByID = function (id) {
  18175. for (var index = 0; index < this.materials.length; index++) {
  18176. if (this.materials[index].id === id) {
  18177. return this.materials[index];
  18178. }
  18179. }
  18180. return null;
  18181. };
  18182. /**
  18183. * get a material using its name
  18184. * @param {string} the material's name
  18185. * @return {BABYLON.Material|null} the material or null if none found.
  18186. */
  18187. Scene.prototype.getMaterialByName = function (name) {
  18188. for (var index = 0; index < this.materials.length; index++) {
  18189. if (this.materials[index].name === name) {
  18190. return this.materials[index];
  18191. }
  18192. }
  18193. return null;
  18194. };
  18195. Scene.prototype.getLensFlareSystemByName = function (name) {
  18196. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18197. if (this.lensFlareSystems[index].name === name) {
  18198. return this.lensFlareSystems[index];
  18199. }
  18200. }
  18201. return null;
  18202. };
  18203. Scene.prototype.getLensFlareSystemByID = function (id) {
  18204. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18205. if (this.lensFlareSystems[index].id === id) {
  18206. return this.lensFlareSystems[index];
  18207. }
  18208. }
  18209. return null;
  18210. };
  18211. Scene.prototype.getCameraByID = function (id) {
  18212. for (var index = 0; index < this.cameras.length; index++) {
  18213. if (this.cameras[index].id === id) {
  18214. return this.cameras[index];
  18215. }
  18216. }
  18217. return null;
  18218. };
  18219. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18220. for (var index = 0; index < this.cameras.length; index++) {
  18221. if (this.cameras[index].uniqueId === uniqueId) {
  18222. return this.cameras[index];
  18223. }
  18224. }
  18225. return null;
  18226. };
  18227. /**
  18228. * get a camera using its name
  18229. * @param {string} the camera's name
  18230. * @return {BABYLON.Camera|null} the camera or null if none found.
  18231. */
  18232. Scene.prototype.getCameraByName = function (name) {
  18233. for (var index = 0; index < this.cameras.length; index++) {
  18234. if (this.cameras[index].name === name) {
  18235. return this.cameras[index];
  18236. }
  18237. }
  18238. return null;
  18239. };
  18240. /**
  18241. * get a bone using its id
  18242. * @param {string} the bone's id
  18243. * @return {BABYLON.Bone|null} the bone or null if not found
  18244. */
  18245. Scene.prototype.getBoneByID = function (id) {
  18246. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18247. var skeleton = this.skeletons[skeletonIndex];
  18248. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18249. if (skeleton.bones[boneIndex].id === id) {
  18250. return skeleton.bones[boneIndex];
  18251. }
  18252. }
  18253. }
  18254. return null;
  18255. };
  18256. /**
  18257. * get a bone using its id
  18258. * @param {string} the bone's name
  18259. * @return {BABYLON.Bone|null} the bone or null if not found
  18260. */
  18261. Scene.prototype.getBoneByName = function (name) {
  18262. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18263. var skeleton = this.skeletons[skeletonIndex];
  18264. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18265. if (skeleton.bones[boneIndex].name === name) {
  18266. return skeleton.bones[boneIndex];
  18267. }
  18268. }
  18269. }
  18270. return null;
  18271. };
  18272. /**
  18273. * get a light node using its name
  18274. * @param {string} the light's name
  18275. * @return {BABYLON.Light|null} the light or null if none found.
  18276. */
  18277. Scene.prototype.getLightByName = function (name) {
  18278. for (var index = 0; index < this.lights.length; index++) {
  18279. if (this.lights[index].name === name) {
  18280. return this.lights[index];
  18281. }
  18282. }
  18283. return null;
  18284. };
  18285. /**
  18286. * get a light node using its ID
  18287. * @param {string} the light's id
  18288. * @return {BABYLON.Light|null} the light or null if none found.
  18289. */
  18290. Scene.prototype.getLightByID = function (id) {
  18291. for (var index = 0; index < this.lights.length; index++) {
  18292. if (this.lights[index].id === id) {
  18293. return this.lights[index];
  18294. }
  18295. }
  18296. return null;
  18297. };
  18298. /**
  18299. * get a light node using its scene-generated unique ID
  18300. * @param {number} the light's unique id
  18301. * @return {BABYLON.Light|null} the light or null if none found.
  18302. */
  18303. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18304. for (var index = 0; index < this.lights.length; index++) {
  18305. if (this.lights[index].uniqueId === uniqueId) {
  18306. return this.lights[index];
  18307. }
  18308. }
  18309. return null;
  18310. };
  18311. /**
  18312. * get a particle system by id
  18313. * @param id {number} the particle system id
  18314. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18315. */
  18316. Scene.prototype.getParticleSystemByID = function (id) {
  18317. for (var index = 0; index < this.particleSystems.length; index++) {
  18318. if (this.particleSystems[index].id === id) {
  18319. return this.particleSystems[index];
  18320. }
  18321. }
  18322. return null;
  18323. };
  18324. /**
  18325. * get a geometry using its ID
  18326. * @param {string} the geometry's id
  18327. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18328. */
  18329. Scene.prototype.getGeometryByID = function (id) {
  18330. for (var index = 0; index < this._geometries.length; index++) {
  18331. if (this._geometries[index].id === id) {
  18332. return this._geometries[index];
  18333. }
  18334. }
  18335. return null;
  18336. };
  18337. /**
  18338. * add a new geometry to this scene.
  18339. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18340. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18341. * @return {boolean} was the geometry added or not
  18342. */
  18343. Scene.prototype.pushGeometry = function (geometry, force) {
  18344. if (!force && this.getGeometryByID(geometry.id)) {
  18345. return false;
  18346. }
  18347. this._geometries.push(geometry);
  18348. //notify the collision coordinator
  18349. if (this.collisionCoordinator) {
  18350. this.collisionCoordinator.onGeometryAdded(geometry);
  18351. }
  18352. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18353. return true;
  18354. };
  18355. /**
  18356. * Removes an existing geometry
  18357. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18358. * @return {boolean} was the geometry removed or not
  18359. */
  18360. Scene.prototype.removeGeometry = function (geometry) {
  18361. var index = this._geometries.indexOf(geometry);
  18362. if (index > -1) {
  18363. this._geometries.splice(index, 1);
  18364. //notify the collision coordinator
  18365. if (this.collisionCoordinator) {
  18366. this.collisionCoordinator.onGeometryDeleted(geometry);
  18367. }
  18368. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18369. return true;
  18370. }
  18371. return false;
  18372. };
  18373. Scene.prototype.getGeometries = function () {
  18374. return this._geometries;
  18375. };
  18376. /**
  18377. * Get the first added mesh found of a given ID
  18378. * @param {string} id - the id to search for
  18379. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18380. */
  18381. Scene.prototype.getMeshByID = function (id) {
  18382. for (var index = 0; index < this.meshes.length; index++) {
  18383. if (this.meshes[index].id === id) {
  18384. return this.meshes[index];
  18385. }
  18386. }
  18387. return null;
  18388. };
  18389. Scene.prototype.getMeshesByID = function (id) {
  18390. return this.meshes.filter(function (m) {
  18391. return m.id === id;
  18392. });
  18393. };
  18394. /**
  18395. * Get a mesh with its auto-generated unique id
  18396. * @param {number} uniqueId - the unique id to search for
  18397. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18398. */
  18399. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18400. for (var index = 0; index < this.meshes.length; index++) {
  18401. if (this.meshes[index].uniqueId === uniqueId) {
  18402. return this.meshes[index];
  18403. }
  18404. }
  18405. return null;
  18406. };
  18407. /**
  18408. * Get a the last added mesh found of a given ID
  18409. * @param {string} id - the id to search for
  18410. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18411. */
  18412. Scene.prototype.getLastMeshByID = function (id) {
  18413. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18414. if (this.meshes[index].id === id) {
  18415. return this.meshes[index];
  18416. }
  18417. }
  18418. return null;
  18419. };
  18420. /**
  18421. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18422. * @param {string} id - the id to search for
  18423. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18424. */
  18425. Scene.prototype.getLastEntryByID = function (id) {
  18426. var index;
  18427. for (index = this.meshes.length - 1; index >= 0; index--) {
  18428. if (this.meshes[index].id === id) {
  18429. return this.meshes[index];
  18430. }
  18431. }
  18432. for (index = this.cameras.length - 1; index >= 0; index--) {
  18433. if (this.cameras[index].id === id) {
  18434. return this.cameras[index];
  18435. }
  18436. }
  18437. for (index = this.lights.length - 1; index >= 0; index--) {
  18438. if (this.lights[index].id === id) {
  18439. return this.lights[index];
  18440. }
  18441. }
  18442. return null;
  18443. };
  18444. Scene.prototype.getNodeByID = function (id) {
  18445. var mesh = this.getMeshByID(id);
  18446. if (mesh) {
  18447. return mesh;
  18448. }
  18449. var light = this.getLightByID(id);
  18450. if (light) {
  18451. return light;
  18452. }
  18453. var camera = this.getCameraByID(id);
  18454. if (camera) {
  18455. return camera;
  18456. }
  18457. var bone = this.getBoneByID(id);
  18458. return bone;
  18459. };
  18460. Scene.prototype.getNodeByName = function (name) {
  18461. var mesh = this.getMeshByName(name);
  18462. if (mesh) {
  18463. return mesh;
  18464. }
  18465. var light = this.getLightByName(name);
  18466. if (light) {
  18467. return light;
  18468. }
  18469. var camera = this.getCameraByName(name);
  18470. if (camera) {
  18471. return camera;
  18472. }
  18473. var bone = this.getBoneByName(name);
  18474. return bone;
  18475. };
  18476. Scene.prototype.getMeshByName = function (name) {
  18477. for (var index = 0; index < this.meshes.length; index++) {
  18478. if (this.meshes[index].name === name) {
  18479. return this.meshes[index];
  18480. }
  18481. }
  18482. return null;
  18483. };
  18484. Scene.prototype.getSoundByName = function (name) {
  18485. var index;
  18486. if (BABYLON.AudioEngine) {
  18487. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18488. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18489. return this.mainSoundTrack.soundCollection[index];
  18490. }
  18491. }
  18492. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18493. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18494. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18495. return this.soundTracks[sdIndex].soundCollection[index];
  18496. }
  18497. }
  18498. }
  18499. }
  18500. return null;
  18501. };
  18502. Scene.prototype.getLastSkeletonByID = function (id) {
  18503. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18504. if (this.skeletons[index].id === id) {
  18505. return this.skeletons[index];
  18506. }
  18507. }
  18508. return null;
  18509. };
  18510. Scene.prototype.getSkeletonById = function (id) {
  18511. for (var index = 0; index < this.skeletons.length; index++) {
  18512. if (this.skeletons[index].id === id) {
  18513. return this.skeletons[index];
  18514. }
  18515. }
  18516. return null;
  18517. };
  18518. Scene.prototype.getSkeletonByName = function (name) {
  18519. for (var index = 0; index < this.skeletons.length; index++) {
  18520. if (this.skeletons[index].name === name) {
  18521. return this.skeletons[index];
  18522. }
  18523. }
  18524. return null;
  18525. };
  18526. Scene.prototype.getMorphTargetManagerById = function (id) {
  18527. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18528. if (this.morphTargetManagers[index].uniqueId === id) {
  18529. return this.morphTargetManagers[index];
  18530. }
  18531. }
  18532. return null;
  18533. };
  18534. Scene.prototype.isActiveMesh = function (mesh) {
  18535. return (this._activeMeshes.indexOf(mesh) !== -1);
  18536. };
  18537. /**
  18538. * Return a the first highlight layer of the scene with a given name.
  18539. * @param name The name of the highlight layer to look for.
  18540. * @return The highlight layer if found otherwise null.
  18541. */
  18542. Scene.prototype.getHighlightLayerByName = function (name) {
  18543. for (var index = 0; index < this.highlightLayers.length; index++) {
  18544. if (this.highlightLayers[index].name === name) {
  18545. return this.highlightLayers[index];
  18546. }
  18547. }
  18548. return null;
  18549. };
  18550. Object.defineProperty(Scene.prototype, "uid", {
  18551. /**
  18552. * Return a unique id as a string which can serve as an identifier for the scene
  18553. */
  18554. get: function () {
  18555. if (!this._uid) {
  18556. this._uid = BABYLON.Tools.RandomId();
  18557. }
  18558. return this._uid;
  18559. },
  18560. enumerable: true,
  18561. configurable: true
  18562. });
  18563. /**
  18564. * Add an externaly attached data from its key.
  18565. * This method call will fail and return false, if such key already exists.
  18566. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18567. * @param key the unique key that identifies the data
  18568. * @param data the data object to associate to the key for this Engine instance
  18569. * @return true if no such key were already present and the data was added successfully, false otherwise
  18570. */
  18571. Scene.prototype.addExternalData = function (key, data) {
  18572. if (!this._externalData) {
  18573. this._externalData = new BABYLON.StringDictionary();
  18574. }
  18575. return this._externalData.add(key, data);
  18576. };
  18577. /**
  18578. * Get an externaly attached data from its key
  18579. * @param key the unique key that identifies the data
  18580. * @return the associated data, if present (can be null), or undefined if not present
  18581. */
  18582. Scene.prototype.getExternalData = function (key) {
  18583. if (!this._externalData) {
  18584. return null;
  18585. }
  18586. return this._externalData.get(key);
  18587. };
  18588. /**
  18589. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18590. * @param key the unique key that identifies the data
  18591. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18592. * @return the associated data, can be null if the factory returned null.
  18593. */
  18594. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18595. if (!this._externalData) {
  18596. this._externalData = new BABYLON.StringDictionary();
  18597. }
  18598. return this._externalData.getOrAddWithFactory(key, factory);
  18599. };
  18600. /**
  18601. * Remove an externaly attached data from the Engine instance
  18602. * @param key the unique key that identifies the data
  18603. * @return true if the data was successfully removed, false if it doesn't exist
  18604. */
  18605. Scene.prototype.removeExternalData = function (key) {
  18606. return this._externalData.remove(key);
  18607. };
  18608. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18609. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18610. var material = subMesh.getMaterial();
  18611. if (mesh.showSubMeshesBoundingBox) {
  18612. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18613. }
  18614. if (material) {
  18615. // Render targets
  18616. if (material.getRenderTargetTextures) {
  18617. if (this._processedMaterials.indexOf(material) === -1) {
  18618. this._processedMaterials.push(material);
  18619. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18620. }
  18621. }
  18622. // Dispatch
  18623. this._activeIndices.addCount(subMesh.indexCount, false);
  18624. this._renderingManager.dispatch(subMesh);
  18625. }
  18626. }
  18627. };
  18628. Scene.prototype._isInIntermediateRendering = function () {
  18629. return this._intermediateRendering;
  18630. };
  18631. /**
  18632. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  18633. */
  18634. Scene.prototype.freezeActiveMeshes = function () {
  18635. this._evaluateActiveMeshes();
  18636. this._activeMeshesFrozen = true;
  18637. return this;
  18638. };
  18639. /**
  18640. * Use this function to restart evaluating active meshes on every frame
  18641. */
  18642. Scene.prototype.unfreezeActiveMeshes = function () {
  18643. this._activeMeshesFrozen = false;
  18644. return this;
  18645. };
  18646. Scene.prototype._evaluateActiveMeshes = function () {
  18647. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  18648. return;
  18649. }
  18650. this.activeCamera._activeMeshes.reset();
  18651. this._activeMeshes.reset();
  18652. this._renderingManager.reset();
  18653. this._processedMaterials.reset();
  18654. this._activeParticleSystems.reset();
  18655. this._activeSkeletons.reset();
  18656. this._softwareSkinnedMeshes.reset();
  18657. if (this._boundingBoxRenderer) {
  18658. this._boundingBoxRenderer.reset();
  18659. }
  18660. // Meshes
  18661. var meshes;
  18662. var len;
  18663. if (this._selectionOctree) {
  18664. var selection = this._selectionOctree.select(this._frustumPlanes);
  18665. meshes = selection.data;
  18666. len = selection.length;
  18667. }
  18668. else {
  18669. len = this.meshes.length;
  18670. meshes = this.meshes;
  18671. }
  18672. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18673. var mesh = meshes[meshIndex];
  18674. if (mesh.isBlocked) {
  18675. continue;
  18676. }
  18677. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18678. if (!mesh.isReady() || !mesh.isEnabled()) {
  18679. continue;
  18680. }
  18681. mesh.computeWorldMatrix();
  18682. // Intersections
  18683. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18684. this._meshesForIntersections.pushNoDuplicate(mesh);
  18685. }
  18686. // Switch to current LOD
  18687. var meshLOD = mesh.getLOD(this.activeCamera);
  18688. if (!meshLOD) {
  18689. continue;
  18690. }
  18691. mesh._preActivate();
  18692. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18693. this._activeMeshes.push(mesh);
  18694. this.activeCamera._activeMeshes.push(mesh);
  18695. mesh._activate(this._renderId);
  18696. if (meshLOD !== mesh) {
  18697. meshLOD._activate(this._renderId);
  18698. }
  18699. this._activeMesh(mesh, meshLOD);
  18700. }
  18701. }
  18702. // Particle systems
  18703. this._particlesDuration.beginMonitoring();
  18704. var beforeParticlesDate = BABYLON.Tools.Now;
  18705. if (this.particlesEnabled) {
  18706. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18707. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18708. var particleSystem = this.particleSystems[particleIndex];
  18709. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18710. continue;
  18711. }
  18712. var emitter = particleSystem.emitter;
  18713. if (!emitter.position || emitter.isEnabled()) {
  18714. this._activeParticleSystems.push(particleSystem);
  18715. particleSystem.animate();
  18716. this._renderingManager.dispatchParticles(particleSystem);
  18717. }
  18718. }
  18719. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18720. }
  18721. this._particlesDuration.endMonitoring(false);
  18722. };
  18723. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18724. if (mesh.skeleton && this.skeletonsEnabled) {
  18725. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18726. mesh.skeleton.prepare();
  18727. }
  18728. if (!mesh.computeBonesUsingShaders) {
  18729. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18730. }
  18731. }
  18732. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18733. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18734. }
  18735. if (mesh && mesh.subMeshes) {
  18736. // Submeshes Octrees
  18737. var len;
  18738. var subMeshes;
  18739. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18740. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18741. len = intersections.length;
  18742. subMeshes = intersections.data;
  18743. }
  18744. else {
  18745. subMeshes = mesh.subMeshes;
  18746. len = subMeshes.length;
  18747. }
  18748. for (var subIndex = 0; subIndex < len; subIndex++) {
  18749. var subMesh = subMeshes[subIndex];
  18750. this._evaluateSubMesh(subMesh, mesh);
  18751. }
  18752. }
  18753. };
  18754. Scene.prototype.updateTransformMatrix = function (force) {
  18755. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18756. };
  18757. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  18758. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  18759. };
  18760. Scene.prototype._renderForCamera = function (camera) {
  18761. if (camera && camera._skipRendering) {
  18762. return;
  18763. }
  18764. var engine = this._engine;
  18765. var startTime = BABYLON.Tools.Now;
  18766. this.activeCamera = camera;
  18767. if (!this.activeCamera)
  18768. throw new Error("Active camera not set");
  18769. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18770. // Viewport
  18771. engine.setViewport(this.activeCamera.viewport);
  18772. // Camera
  18773. this.resetCachedMaterial();
  18774. this._renderId++;
  18775. this.activeCamera.update();
  18776. this.updateTransformMatrix();
  18777. if (camera._alternateCamera) {
  18778. this.updateAlternateTransformMatrix(camera._alternateCamera);
  18779. this._alternateRendering = true;
  18780. }
  18781. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18782. // Meshes
  18783. this._evaluateActiveMeshesDuration.beginMonitoring();
  18784. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18785. this._evaluateActiveMeshes();
  18786. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18787. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18788. // Software skinning
  18789. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18790. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18791. mesh.applySkeleton(mesh.skeleton);
  18792. }
  18793. // Render targets
  18794. this._renderTargetsDuration.beginMonitoring();
  18795. var needsRestoreFrameBuffer = false;
  18796. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18797. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18798. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18799. }
  18800. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18801. this._intermediateRendering = true;
  18802. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18803. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18804. var renderTarget = this._renderTargets.data[renderIndex];
  18805. if (renderTarget._shouldRender()) {
  18806. this._renderId++;
  18807. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18808. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18809. }
  18810. }
  18811. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18812. this._intermediateRendering = false;
  18813. this._renderId++;
  18814. needsRestoreFrameBuffer = true; // Restore back buffer
  18815. }
  18816. // Render HighlightLayer Texture
  18817. var stencilState = this._engine.getStencilBuffer();
  18818. var renderhighlights = false;
  18819. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18820. this._intermediateRendering = true;
  18821. for (var i = 0; i < this.highlightLayers.length; i++) {
  18822. var highlightLayer = this.highlightLayers[i];
  18823. if (highlightLayer.shouldRender() &&
  18824. (!highlightLayer.camera ||
  18825. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18826. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18827. renderhighlights = true;
  18828. var renderTarget = highlightLayer._mainTexture;
  18829. if (renderTarget._shouldRender()) {
  18830. this._renderId++;
  18831. renderTarget.render(false, false);
  18832. needsRestoreFrameBuffer = true;
  18833. }
  18834. }
  18835. }
  18836. this._intermediateRendering = false;
  18837. this._renderId++;
  18838. }
  18839. if (needsRestoreFrameBuffer) {
  18840. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18841. }
  18842. this._renderTargetsDuration.endMonitoring(false);
  18843. // Prepare Frame
  18844. this.postProcessManager._prepareFrame();
  18845. this._renderDuration.beginMonitoring();
  18846. // Backgrounds
  18847. var layerIndex;
  18848. var layer;
  18849. if (this.layers.length) {
  18850. engine.setDepthBuffer(false);
  18851. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18852. layer = this.layers[layerIndex];
  18853. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18854. layer.render();
  18855. }
  18856. }
  18857. engine.setDepthBuffer(true);
  18858. }
  18859. // Render
  18860. BABYLON.Tools.StartPerformanceCounter("Main render");
  18861. // Activate HighlightLayer stencil
  18862. if (renderhighlights) {
  18863. this._engine.setStencilBuffer(true);
  18864. }
  18865. this._renderingManager.render(null, null, true, true);
  18866. // Restore HighlightLayer stencil
  18867. if (renderhighlights) {
  18868. this._engine.setStencilBuffer(stencilState);
  18869. }
  18870. BABYLON.Tools.EndPerformanceCounter("Main render");
  18871. // Bounding boxes
  18872. if (this._boundingBoxRenderer) {
  18873. this._boundingBoxRenderer.render();
  18874. }
  18875. // Lens flares
  18876. if (this.lensFlaresEnabled) {
  18877. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18878. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18879. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18880. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18881. lensFlareSystem.render();
  18882. }
  18883. }
  18884. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18885. }
  18886. // Foregrounds
  18887. if (this.layers.length) {
  18888. engine.setDepthBuffer(false);
  18889. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18890. layer = this.layers[layerIndex];
  18891. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18892. layer.render();
  18893. }
  18894. }
  18895. engine.setDepthBuffer(true);
  18896. }
  18897. // Highlight Layer
  18898. if (renderhighlights) {
  18899. engine.setDepthBuffer(false);
  18900. for (var i = 0; i < this.highlightLayers.length; i++) {
  18901. if (this.highlightLayers[i].shouldRender()) {
  18902. this.highlightLayers[i].render();
  18903. }
  18904. }
  18905. engine.setDepthBuffer(true);
  18906. }
  18907. this._renderDuration.endMonitoring(false);
  18908. // Finalize frame
  18909. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18910. // Reset some special arrays
  18911. this._renderTargets.reset();
  18912. this._alternateRendering = false;
  18913. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18914. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18915. };
  18916. Scene.prototype._processSubCameras = function (camera) {
  18917. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18918. this._renderForCamera(camera);
  18919. return;
  18920. }
  18921. // Update camera
  18922. this.activeCamera.update();
  18923. // rig cameras
  18924. for (var index = 0; index < camera._rigCameras.length; index++) {
  18925. this._renderForCamera(camera._rigCameras[index]);
  18926. }
  18927. this.activeCamera = camera;
  18928. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18929. };
  18930. Scene.prototype._checkIntersections = function () {
  18931. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18932. var sourceMesh = this._meshesForIntersections.data[index];
  18933. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18934. var action = sourceMesh.actionManager.actions[actionIndex];
  18935. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18936. var parameters = action.getTriggerParameter();
  18937. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18938. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18939. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18940. if (areIntersecting && currentIntersectionInProgress === -1) {
  18941. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18942. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18943. sourceMesh._intersectionsInProgress.push(otherMesh);
  18944. }
  18945. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18946. sourceMesh._intersectionsInProgress.push(otherMesh);
  18947. }
  18948. }
  18949. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18950. //They intersected, and now they don't.
  18951. //is this trigger an exit trigger? execute an event.
  18952. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18953. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18954. }
  18955. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18956. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18957. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18958. }
  18959. }
  18960. }
  18961. }
  18962. }
  18963. };
  18964. Scene.prototype.render = function () {
  18965. if (this.isDisposed) {
  18966. return;
  18967. }
  18968. this._interFrameDuration.endMonitoring();
  18969. this._lastFrameDuration.beginMonitoring();
  18970. this._particlesDuration.fetchNewFrame();
  18971. this._spritesDuration.fetchNewFrame();
  18972. this._activeParticles.fetchNewFrame();
  18973. this._renderDuration.fetchNewFrame();
  18974. this._renderTargetsDuration.fetchNewFrame();
  18975. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18976. this._totalVertices.fetchNewFrame();
  18977. this._activeIndices.fetchNewFrame();
  18978. this._activeBones.fetchNewFrame();
  18979. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18980. this._meshesForIntersections.reset();
  18981. this.resetCachedMaterial();
  18982. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18983. // Actions
  18984. if (this.actionManager) {
  18985. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18986. }
  18987. //Simplification Queue
  18988. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18989. this.simplificationQueue.executeNext();
  18990. }
  18991. if (this._engine.isDeterministicLockStep()) {
  18992. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18993. var defaultTimeStep = (60.0 / 1000.0);
  18994. if (this._physicsEngine) {
  18995. defaultTimeStep = this._physicsEngine.getTimeStep();
  18996. }
  18997. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18998. this._timeAccumulator += deltaTime;
  18999. // compute the amount of fixed steps we should have taken since the last step
  19000. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19001. internalSteps = Math.min(internalSteps, maxSubSteps);
  19002. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19003. this.onBeforeStepObservable.notifyObservers(this);
  19004. // Animations
  19005. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19006. this._animate();
  19007. // Physics
  19008. if (this._physicsEngine) {
  19009. BABYLON.Tools.StartPerformanceCounter("Physics");
  19010. this._physicsEngine._step(defaultTimeStep);
  19011. BABYLON.Tools.EndPerformanceCounter("Physics");
  19012. }
  19013. this._timeAccumulator -= defaultTimeStep;
  19014. this.onAfterStepObservable.notifyObservers(this);
  19015. this._currentStepId++;
  19016. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19017. this._evaluateActiveMeshes();
  19018. }
  19019. }
  19020. }
  19021. else {
  19022. // Animations
  19023. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19024. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19025. this._animate();
  19026. // Physics
  19027. if (this._physicsEngine) {
  19028. BABYLON.Tools.StartPerformanceCounter("Physics");
  19029. this._physicsEngine._step(deltaTime / 1000.0);
  19030. BABYLON.Tools.EndPerformanceCounter("Physics");
  19031. }
  19032. }
  19033. // Before render
  19034. this.onBeforeRenderObservable.notifyObservers(this);
  19035. // Customs render targets
  19036. this._renderTargetsDuration.beginMonitoring();
  19037. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19038. var engine = this.getEngine();
  19039. var currentActiveCamera = this.activeCamera;
  19040. if (this.renderTargetsEnabled) {
  19041. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19042. this._intermediateRendering = true;
  19043. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19044. var renderTarget = this.customRenderTargets[customIndex];
  19045. if (renderTarget._shouldRender()) {
  19046. this._renderId++;
  19047. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19048. if (!this.activeCamera)
  19049. throw new Error("Active camera not set");
  19050. // Viewport
  19051. engine.setViewport(this.activeCamera.viewport);
  19052. // Camera
  19053. this.updateTransformMatrix();
  19054. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19055. }
  19056. }
  19057. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19058. this._intermediateRendering = false;
  19059. this._renderId++;
  19060. }
  19061. // Restore back buffer
  19062. if (this.customRenderTargets.length > 0) {
  19063. engine.restoreDefaultFramebuffer();
  19064. }
  19065. this._renderTargetsDuration.endMonitoring();
  19066. this.activeCamera = currentActiveCamera;
  19067. // Procedural textures
  19068. if (this.proceduralTexturesEnabled) {
  19069. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19070. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19071. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19072. if (proceduralTexture._shouldRender()) {
  19073. proceduralTexture.render();
  19074. }
  19075. }
  19076. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19077. }
  19078. // Clear
  19079. if (this.autoClearDepthAndStencil || this.autoClear) {
  19080. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19081. }
  19082. // Shadows
  19083. if (this.shadowsEnabled) {
  19084. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19085. var light = this.lights[lightIndex];
  19086. var shadowGenerator = light.getShadowGenerator();
  19087. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19088. var shadowMap = shadowGenerator.getShadowMap();
  19089. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  19090. this._renderTargets.push(shadowMap);
  19091. }
  19092. }
  19093. }
  19094. }
  19095. // Depth renderer
  19096. if (this._depthRenderer) {
  19097. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19098. }
  19099. // Geometry renderer
  19100. if (this._geometryBufferRenderer) {
  19101. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19102. }
  19103. // RenderPipeline
  19104. if (this._postProcessRenderPipelineManager) {
  19105. this._postProcessRenderPipelineManager.update();
  19106. }
  19107. // Multi-cameras?
  19108. if (this.activeCameras.length > 0) {
  19109. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19110. if (cameraIndex > 0) {
  19111. this._engine.clear(null, false, true, true);
  19112. }
  19113. this._processSubCameras(this.activeCameras[cameraIndex]);
  19114. }
  19115. }
  19116. else {
  19117. if (!this.activeCamera) {
  19118. throw new Error("No camera defined");
  19119. }
  19120. this._processSubCameras(this.activeCamera);
  19121. }
  19122. // Intersection checks
  19123. this._checkIntersections();
  19124. // Update the audio listener attached to the camera
  19125. if (BABYLON.AudioEngine) {
  19126. this._updateAudioParameters();
  19127. }
  19128. // After render
  19129. if (this.afterRender) {
  19130. this.afterRender();
  19131. }
  19132. this.onAfterRenderObservable.notifyObservers(this);
  19133. // Cleaning
  19134. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19135. this._toBeDisposed.data[index].dispose();
  19136. this._toBeDisposed[index] = null;
  19137. }
  19138. this._toBeDisposed.reset();
  19139. if (this.dumpNextRenderTargets) {
  19140. this.dumpNextRenderTargets = false;
  19141. }
  19142. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19143. this._interFrameDuration.beginMonitoring();
  19144. this._lastFrameDuration.endMonitoring();
  19145. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19146. this._totalLightsCounter.addCount(this.lights.length, true);
  19147. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19148. this._totalTexturesCounter.addCount(this.textures.length, true);
  19149. this._activeBones.addCount(0, true);
  19150. this._activeIndices.addCount(0, true);
  19151. this._activeParticles.addCount(0, true);
  19152. };
  19153. Scene.prototype._updateAudioParameters = function () {
  19154. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19155. return;
  19156. }
  19157. var listeningCamera;
  19158. var audioEngine = BABYLON.Engine.audioEngine;
  19159. if (this.activeCameras.length > 0) {
  19160. listeningCamera = this.activeCameras[0];
  19161. }
  19162. else {
  19163. listeningCamera = this.activeCamera;
  19164. }
  19165. if (listeningCamera && audioEngine.canUseWebAudio) {
  19166. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19167. // for VR cameras
  19168. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19169. listeningCamera = listeningCamera.rigCameras[0];
  19170. }
  19171. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19172. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19173. cameraDirection.normalize();
  19174. // To avoid some errors on GearVR
  19175. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19176. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19177. }
  19178. var i;
  19179. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19180. var sound = this.mainSoundTrack.soundCollection[i];
  19181. if (sound.useCustomAttenuation) {
  19182. sound.updateDistanceFromListener();
  19183. }
  19184. }
  19185. for (i = 0; i < this.soundTracks.length; i++) {
  19186. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19187. sound = this.soundTracks[i].soundCollection[j];
  19188. if (sound.useCustomAttenuation) {
  19189. sound.updateDistanceFromListener();
  19190. }
  19191. }
  19192. }
  19193. }
  19194. };
  19195. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19196. // Audio
  19197. get: function () {
  19198. return this._audioEnabled;
  19199. },
  19200. set: function (value) {
  19201. this._audioEnabled = value;
  19202. if (BABYLON.AudioEngine) {
  19203. if (this._audioEnabled) {
  19204. this._enableAudio();
  19205. }
  19206. else {
  19207. this._disableAudio();
  19208. }
  19209. }
  19210. },
  19211. enumerable: true,
  19212. configurable: true
  19213. });
  19214. Scene.prototype._disableAudio = function () {
  19215. var i;
  19216. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19217. this.mainSoundTrack.soundCollection[i].pause();
  19218. }
  19219. for (i = 0; i < this.soundTracks.length; i++) {
  19220. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19221. this.soundTracks[i].soundCollection[j].pause();
  19222. }
  19223. }
  19224. };
  19225. Scene.prototype._enableAudio = function () {
  19226. var i;
  19227. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19228. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19229. this.mainSoundTrack.soundCollection[i].play();
  19230. }
  19231. }
  19232. for (i = 0; i < this.soundTracks.length; i++) {
  19233. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19234. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19235. this.soundTracks[i].soundCollection[j].play();
  19236. }
  19237. }
  19238. }
  19239. };
  19240. Object.defineProperty(Scene.prototype, "headphone", {
  19241. get: function () {
  19242. return this._headphone;
  19243. },
  19244. set: function (value) {
  19245. this._headphone = value;
  19246. if (BABYLON.AudioEngine) {
  19247. if (this._headphone) {
  19248. this._switchAudioModeForHeadphones();
  19249. }
  19250. else {
  19251. this._switchAudioModeForNormalSpeakers();
  19252. }
  19253. }
  19254. },
  19255. enumerable: true,
  19256. configurable: true
  19257. });
  19258. Scene.prototype._switchAudioModeForHeadphones = function () {
  19259. this.mainSoundTrack.switchPanningModelToHRTF();
  19260. for (var i = 0; i < this.soundTracks.length; i++) {
  19261. this.soundTracks[i].switchPanningModelToHRTF();
  19262. }
  19263. };
  19264. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19265. this.mainSoundTrack.switchPanningModelToEqualPower();
  19266. for (var i = 0; i < this.soundTracks.length; i++) {
  19267. this.soundTracks[i].switchPanningModelToEqualPower();
  19268. }
  19269. };
  19270. Scene.prototype.enableDepthRenderer = function () {
  19271. if (this._depthRenderer) {
  19272. return this._depthRenderer;
  19273. }
  19274. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19275. return this._depthRenderer;
  19276. };
  19277. Scene.prototype.disableDepthRenderer = function () {
  19278. if (!this._depthRenderer) {
  19279. return;
  19280. }
  19281. this._depthRenderer.dispose();
  19282. this._depthRenderer = null;
  19283. };
  19284. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19285. if (ratio === void 0) { ratio = 1; }
  19286. if (this._geometryBufferRenderer) {
  19287. return this._geometryBufferRenderer;
  19288. }
  19289. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19290. if (!this._geometryBufferRenderer.isSupported) {
  19291. this._geometryBufferRenderer = null;
  19292. }
  19293. return this._geometryBufferRenderer;
  19294. };
  19295. Scene.prototype.disableGeometryBufferRenderer = function () {
  19296. if (!this._geometryBufferRenderer) {
  19297. return;
  19298. }
  19299. this._geometryBufferRenderer.dispose();
  19300. this._geometryBufferRenderer = null;
  19301. };
  19302. Scene.prototype.freezeMaterials = function () {
  19303. for (var i = 0; i < this.materials.length; i++) {
  19304. this.materials[i].freeze();
  19305. }
  19306. };
  19307. Scene.prototype.unfreezeMaterials = function () {
  19308. for (var i = 0; i < this.materials.length; i++) {
  19309. this.materials[i].unfreeze();
  19310. }
  19311. };
  19312. Scene.prototype.dispose = function () {
  19313. this.beforeRender = null;
  19314. this.afterRender = null;
  19315. this.skeletons = [];
  19316. this.morphTargetManagers = [];
  19317. this.importedMeshesFiles = new Array();
  19318. this.resetCachedMaterial();
  19319. if (this._depthRenderer) {
  19320. this._depthRenderer.dispose();
  19321. }
  19322. if (this._gamepadManager) {
  19323. this._gamepadManager.dispose();
  19324. this._gamepadManager = null;
  19325. }
  19326. // Smart arrays
  19327. if (this.activeCamera) {
  19328. this.activeCamera._activeMeshes.dispose();
  19329. this.activeCamera = null;
  19330. }
  19331. this._activeMeshes.dispose();
  19332. this._renderingManager.dispose();
  19333. this._processedMaterials.dispose();
  19334. this._activeParticleSystems.dispose();
  19335. this._activeSkeletons.dispose();
  19336. this._softwareSkinnedMeshes.dispose();
  19337. this._renderTargets.dispose();
  19338. if (this._boundingBoxRenderer) {
  19339. this._boundingBoxRenderer.dispose();
  19340. }
  19341. this._meshesForIntersections.dispose();
  19342. this._toBeDisposed.dispose();
  19343. // Debug layer
  19344. if (this._debugLayer) {
  19345. this._debugLayer.hide();
  19346. }
  19347. // Events
  19348. this.onDisposeObservable.notifyObservers(this);
  19349. this.onDisposeObservable.clear();
  19350. this.onBeforeRenderObservable.clear();
  19351. this.onAfterRenderObservable.clear();
  19352. this.detachControl();
  19353. // Release sounds & sounds tracks
  19354. if (BABYLON.AudioEngine) {
  19355. this.disposeSounds();
  19356. }
  19357. // VR Helper
  19358. if (this.VRHelper) {
  19359. this.VRHelper.dispose();
  19360. }
  19361. // Detach cameras
  19362. var canvas = this._engine.getRenderingCanvas();
  19363. var index;
  19364. for (index = 0; index < this.cameras.length; index++) {
  19365. this.cameras[index].detachControl(canvas);
  19366. }
  19367. // Release lights
  19368. while (this.lights.length) {
  19369. this.lights[0].dispose();
  19370. }
  19371. // Release meshes
  19372. while (this.meshes.length) {
  19373. this.meshes[0].dispose(true);
  19374. }
  19375. // Release cameras
  19376. while (this.cameras.length) {
  19377. this.cameras[0].dispose();
  19378. }
  19379. // Release materials
  19380. if (this.defaultMaterial) {
  19381. this.defaultMaterial.dispose();
  19382. }
  19383. while (this.multiMaterials.length) {
  19384. this.multiMaterials[0].dispose();
  19385. }
  19386. while (this.materials.length) {
  19387. this.materials[0].dispose();
  19388. }
  19389. // Release particles
  19390. while (this.particleSystems.length) {
  19391. this.particleSystems[0].dispose();
  19392. }
  19393. // Release sprites
  19394. while (this.spriteManagers.length) {
  19395. this.spriteManagers[0].dispose();
  19396. }
  19397. // Release postProcesses
  19398. while (this.postProcesses.length) {
  19399. this.postProcesses[0].dispose();
  19400. }
  19401. // Release layers
  19402. while (this.layers.length) {
  19403. this.layers[0].dispose();
  19404. }
  19405. while (this.highlightLayers.length) {
  19406. this.highlightLayers[0].dispose();
  19407. }
  19408. // Release textures
  19409. while (this.textures.length) {
  19410. this.textures[0].dispose();
  19411. }
  19412. // Release UBO
  19413. this._sceneUbo.dispose();
  19414. if (this._alternateSceneUbo) {
  19415. this._alternateSceneUbo.dispose();
  19416. }
  19417. // Post-processes
  19418. this.postProcessManager.dispose();
  19419. if (this._postProcessRenderPipelineManager) {
  19420. this._postProcessRenderPipelineManager.dispose();
  19421. }
  19422. // Physics
  19423. if (this._physicsEngine) {
  19424. this.disablePhysicsEngine();
  19425. }
  19426. // Remove from engine
  19427. index = this._engine.scenes.indexOf(this);
  19428. if (index > -1) {
  19429. this._engine.scenes.splice(index, 1);
  19430. }
  19431. this._engine.wipeCaches();
  19432. this._engine = null;
  19433. this.defaultMaterial = null;
  19434. this.multiMaterials = null;
  19435. this.materials = null;
  19436. };
  19437. Object.defineProperty(Scene.prototype, "isDisposed", {
  19438. get: function () {
  19439. return !this._engine;
  19440. },
  19441. enumerable: true,
  19442. configurable: true
  19443. });
  19444. // Release sounds & sounds tracks
  19445. Scene.prototype.disposeSounds = function () {
  19446. this.mainSoundTrack.dispose();
  19447. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19448. this.soundTracks[scIndex].dispose();
  19449. }
  19450. };
  19451. // Octrees
  19452. Scene.prototype.getWorldExtends = function () {
  19453. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19454. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19455. for (var index = 0; index < this.meshes.length; index++) {
  19456. var mesh = this.meshes[index];
  19457. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19458. continue;
  19459. }
  19460. mesh.computeWorldMatrix(true);
  19461. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19462. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19463. BABYLON.Tools.CheckExtends(minBox, min, max);
  19464. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19465. }
  19466. return {
  19467. min: min,
  19468. max: max
  19469. };
  19470. };
  19471. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19472. if (maxCapacity === void 0) { maxCapacity = 64; }
  19473. if (maxDepth === void 0) { maxDepth = 2; }
  19474. if (!this._selectionOctree) {
  19475. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19476. }
  19477. var worldExtends = this.getWorldExtends();
  19478. // Update octree
  19479. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19480. return this._selectionOctree;
  19481. };
  19482. // Picking
  19483. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19484. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19485. var engine = this._engine;
  19486. if (!camera) {
  19487. if (!this.activeCamera)
  19488. throw new Error("Active camera not set");
  19489. camera = this.activeCamera;
  19490. }
  19491. var cameraViewport = camera.viewport;
  19492. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19493. // Moving coordinates to local viewport world
  19494. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19495. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19496. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19497. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19498. };
  19499. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19500. if (!BABYLON.PickingInfo) {
  19501. return null;
  19502. }
  19503. var engine = this._engine;
  19504. if (!camera) {
  19505. if (!this.activeCamera)
  19506. throw new Error("Active camera not set");
  19507. camera = this.activeCamera;
  19508. }
  19509. var cameraViewport = camera.viewport;
  19510. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19511. var identity = BABYLON.Matrix.Identity();
  19512. // Moving coordinates to local viewport world
  19513. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19514. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19515. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19516. };
  19517. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19518. if (!BABYLON.PickingInfo) {
  19519. return null;
  19520. }
  19521. var pickingInfo = null;
  19522. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19523. var mesh = this.meshes[meshIndex];
  19524. if (predicate) {
  19525. if (!predicate(mesh)) {
  19526. continue;
  19527. }
  19528. }
  19529. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19530. continue;
  19531. }
  19532. var world = mesh.getWorldMatrix();
  19533. var ray = rayFunction(world);
  19534. var result = mesh.intersects(ray, fastCheck);
  19535. if (!result || !result.hit)
  19536. continue;
  19537. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19538. continue;
  19539. pickingInfo = result;
  19540. if (fastCheck) {
  19541. break;
  19542. }
  19543. }
  19544. return pickingInfo || new BABYLON.PickingInfo();
  19545. };
  19546. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19547. if (!BABYLON.PickingInfo) {
  19548. return null;
  19549. }
  19550. var pickingInfos = new Array();
  19551. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19552. var mesh = this.meshes[meshIndex];
  19553. if (predicate) {
  19554. if (!predicate(mesh)) {
  19555. continue;
  19556. }
  19557. }
  19558. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19559. continue;
  19560. }
  19561. var world = mesh.getWorldMatrix();
  19562. var ray = rayFunction(world);
  19563. var result = mesh.intersects(ray, false);
  19564. if (!result || !result.hit)
  19565. continue;
  19566. pickingInfos.push(result);
  19567. }
  19568. return pickingInfos;
  19569. };
  19570. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19571. if (!BABYLON.PickingInfo) {
  19572. return null;
  19573. }
  19574. var pickingInfo = null;
  19575. camera = camera || this.activeCamera;
  19576. if (this.spriteManagers.length > 0) {
  19577. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19578. var spriteManager = this.spriteManagers[spriteIndex];
  19579. if (!spriteManager.isPickable) {
  19580. continue;
  19581. }
  19582. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19583. if (!result || !result.hit)
  19584. continue;
  19585. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19586. continue;
  19587. pickingInfo = result;
  19588. if (fastCheck) {
  19589. break;
  19590. }
  19591. }
  19592. }
  19593. return pickingInfo || new BABYLON.PickingInfo();
  19594. };
  19595. /** Launch a ray to try to pick a mesh in the scene
  19596. * @param x position on screen
  19597. * @param y position on screen
  19598. * @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
  19599. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19600. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19601. */
  19602. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19603. var _this = this;
  19604. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19605. };
  19606. /** Launch a ray to try to pick a sprite in the scene
  19607. * @param x position on screen
  19608. * @param y position on screen
  19609. * @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
  19610. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19611. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19612. */
  19613. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19614. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19615. };
  19616. /** Use the given ray to pick a mesh in the scene
  19617. * @param ray The ray to use to pick meshes
  19618. * @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
  19619. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19620. */
  19621. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19622. var _this = this;
  19623. return this._internalPick(function (world) {
  19624. if (!_this._pickWithRayInverseMatrix) {
  19625. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19626. }
  19627. world.invertToRef(_this._pickWithRayInverseMatrix);
  19628. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19629. }, predicate, fastCheck);
  19630. };
  19631. /**
  19632. * Launch a ray to try to pick a mesh in the scene
  19633. * @param x X position on screen
  19634. * @param y Y position on screen
  19635. * @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
  19636. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19637. */
  19638. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19639. var _this = this;
  19640. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19641. };
  19642. /**
  19643. * Launch a ray to try to pick a mesh in the scene
  19644. * @param ray Ray to use
  19645. * @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
  19646. */
  19647. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19648. var _this = this;
  19649. return this._internalMultiPick(function (world) {
  19650. if (!_this._pickWithRayInverseMatrix) {
  19651. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19652. }
  19653. world.invertToRef(_this._pickWithRayInverseMatrix);
  19654. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19655. }, predicate);
  19656. };
  19657. Scene.prototype.setPointerOverMesh = function (mesh) {
  19658. if (this._pointerOverMesh === mesh) {
  19659. return;
  19660. }
  19661. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19662. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19663. }
  19664. this._pointerOverMesh = mesh;
  19665. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19666. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19667. }
  19668. };
  19669. Scene.prototype.getPointerOverMesh = function () {
  19670. return this._pointerOverMesh;
  19671. };
  19672. Scene.prototype.setPointerOverSprite = function (sprite) {
  19673. if (this._pointerOverSprite === sprite) {
  19674. return;
  19675. }
  19676. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19677. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19678. }
  19679. this._pointerOverSprite = sprite;
  19680. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19681. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19682. }
  19683. };
  19684. Scene.prototype.getPointerOverSprite = function () {
  19685. return this._pointerOverSprite;
  19686. };
  19687. // Physics
  19688. Scene.prototype.getPhysicsEngine = function () {
  19689. return this._physicsEngine;
  19690. };
  19691. /**
  19692. * Enables physics to the current scene
  19693. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19694. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19695. * @return {boolean} was the physics engine initialized
  19696. */
  19697. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19698. if (this._physicsEngine) {
  19699. return true;
  19700. }
  19701. try {
  19702. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19703. return true;
  19704. }
  19705. catch (e) {
  19706. BABYLON.Tools.Error(e.message);
  19707. return false;
  19708. }
  19709. };
  19710. Scene.prototype.disablePhysicsEngine = function () {
  19711. if (!this._physicsEngine) {
  19712. return;
  19713. }
  19714. this._physicsEngine.dispose();
  19715. this._physicsEngine = undefined;
  19716. };
  19717. Scene.prototype.isPhysicsEnabled = function () {
  19718. return this._physicsEngine !== undefined;
  19719. };
  19720. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19721. var mesh = compound.parts[0].mesh;
  19722. mesh.physicsImpostor.dispose();
  19723. mesh.physicsImpostor = null;
  19724. };
  19725. // Misc.
  19726. Scene.prototype._rebuildGeometries = function () {
  19727. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19728. var geometry = _a[_i];
  19729. geometry._rebuild();
  19730. }
  19731. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19732. var mesh = _c[_b];
  19733. mesh._rebuild();
  19734. }
  19735. if (this.postProcessManager) {
  19736. this.postProcessManager._rebuild();
  19737. }
  19738. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19739. var layer = _e[_d];
  19740. layer._rebuild();
  19741. }
  19742. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19743. var highlightLayer = _g[_f];
  19744. highlightLayer._rebuild();
  19745. }
  19746. if (this._boundingBoxRenderer) {
  19747. this._boundingBoxRenderer._rebuild();
  19748. }
  19749. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19750. var system = _j[_h];
  19751. system.rebuild();
  19752. }
  19753. if (this._postProcessRenderPipelineManager) {
  19754. this._postProcessRenderPipelineManager._rebuild();
  19755. }
  19756. };
  19757. Scene.prototype._rebuildTextures = function () {
  19758. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19759. var texture = _a[_i];
  19760. texture._rebuild();
  19761. }
  19762. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19763. };
  19764. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19765. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19766. if (replace === void 0) { replace = false; }
  19767. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19768. // Dispose existing camera or light in replace mode.
  19769. if (replace) {
  19770. if (this.activeCamera) {
  19771. this.activeCamera.dispose();
  19772. this.activeCamera = null;
  19773. }
  19774. if (this.lights) {
  19775. for (var i = 0; i < this.lights.length; i++) {
  19776. this.lights[i].dispose();
  19777. }
  19778. }
  19779. }
  19780. // Light
  19781. if (this.lights.length === 0) {
  19782. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19783. }
  19784. // Camera
  19785. if (!this.activeCamera) {
  19786. var worldExtends = this.getWorldExtends();
  19787. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19788. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19789. var camera;
  19790. var radius = worldSize.length() * 1.5;
  19791. if (createArcRotateCamera) {
  19792. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19793. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19794. arcRotateCamera.wheelPrecision = 100 / radius;
  19795. camera = arcRotateCamera;
  19796. }
  19797. else {
  19798. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19799. freeCamera.setTarget(worldCenter);
  19800. camera = freeCamera;
  19801. }
  19802. camera.minZ = radius * 0.01;
  19803. camera.maxZ = radius * 100;
  19804. camera.speed = radius * 0.2;
  19805. this.activeCamera = camera;
  19806. if (attachCameraControls) {
  19807. camera.attachControl(this.getEngine().getRenderingCanvas());
  19808. }
  19809. }
  19810. };
  19811. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19812. if (pbr === void 0) { pbr = false; }
  19813. if (scale === void 0) { scale = 1000; }
  19814. if (blur === void 0) { blur = 0; }
  19815. if (environmentTexture) {
  19816. this.environmentTexture = environmentTexture;
  19817. }
  19818. if (!this.environmentTexture) {
  19819. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19820. return;
  19821. }
  19822. // Skybox
  19823. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19824. if (pbr) {
  19825. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19826. hdrSkyboxMaterial.backFaceCulling = false;
  19827. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19828. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19829. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19830. hdrSkyboxMaterial.disableLighting = true;
  19831. hdrSkyboxMaterial.twoSidedLighting = true;
  19832. hdrSkybox.infiniteDistance = true;
  19833. hdrSkybox.material = hdrSkyboxMaterial;
  19834. }
  19835. else {
  19836. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19837. skyboxMaterial.backFaceCulling = false;
  19838. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19839. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19840. skyboxMaterial.disableLighting = true;
  19841. hdrSkybox.infiniteDistance = true;
  19842. hdrSkybox.material = skyboxMaterial;
  19843. }
  19844. return hdrSkybox;
  19845. };
  19846. Scene.prototype.createDefaultVRExperience = function () {
  19847. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19848. };
  19849. // Tags
  19850. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19851. if (tagsQuery === undefined) {
  19852. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19853. return list;
  19854. }
  19855. var listByTags = [];
  19856. forEach = forEach || (function (item) { return; });
  19857. for (var i in list) {
  19858. var item = list[i];
  19859. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19860. listByTags.push(item);
  19861. forEach(item);
  19862. }
  19863. }
  19864. return listByTags;
  19865. };
  19866. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19867. return this._getByTags(this.meshes, tagsQuery, forEach);
  19868. };
  19869. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19870. return this._getByTags(this.cameras, tagsQuery, forEach);
  19871. };
  19872. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19873. return this._getByTags(this.lights, tagsQuery, forEach);
  19874. };
  19875. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19876. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19877. };
  19878. /**
  19879. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19880. * This allowed control for front to back rendering or reversly depending of the special needs.
  19881. *
  19882. * @param renderingGroupId The rendering group id corresponding to its index
  19883. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19884. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19885. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19886. */
  19887. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19888. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19889. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19890. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19891. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19892. };
  19893. /**
  19894. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19895. *
  19896. * @param renderingGroupId The rendering group id corresponding to its index
  19897. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19898. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19899. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19900. */
  19901. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19902. if (depth === void 0) { depth = true; }
  19903. if (stencil === void 0) { stencil = true; }
  19904. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19905. };
  19906. /**
  19907. * Will flag all materials as dirty to trigger new shader compilation
  19908. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19909. */
  19910. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19911. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19912. var material = _a[_i];
  19913. if (predicate && !predicate(material)) {
  19914. continue;
  19915. }
  19916. material.markAsDirty(flag);
  19917. }
  19918. };
  19919. // Statics
  19920. Scene._FOGMODE_NONE = 0;
  19921. Scene._FOGMODE_EXP = 1;
  19922. Scene._FOGMODE_EXP2 = 2;
  19923. Scene._FOGMODE_LINEAR = 3;
  19924. Scene.MinDeltaTime = 1.0;
  19925. Scene.MaxDeltaTime = 1000.0;
  19926. /** The distance in pixel that you have to move to prevent some events */
  19927. Scene.DragMovementThreshold = 10; // in pixels
  19928. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19929. Scene.LongPressDelay = 500; // in milliseconds
  19930. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19931. Scene.DoubleClickDelay = 300; // in milliseconds
  19932. /** If you need to check double click without raising a single click at first click, enable this flag */
  19933. Scene.ExclusiveDoubleClickMode = false;
  19934. return Scene;
  19935. }());
  19936. BABYLON.Scene = Scene;
  19937. })(BABYLON || (BABYLON = {}));
  19938. //# sourceMappingURL=babylon.scene.js.map
  19939. var BABYLON;
  19940. (function (BABYLON) {
  19941. var Buffer = (function () {
  19942. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19943. if (engine instanceof BABYLON.Mesh) {
  19944. this._engine = engine.getScene().getEngine();
  19945. }
  19946. else {
  19947. this._engine = engine;
  19948. }
  19949. this._updatable = updatable;
  19950. this._data = data;
  19951. this._strideSize = stride;
  19952. if (!postponeInternalCreation) {
  19953. this.create();
  19954. }
  19955. this._instanced = instanced;
  19956. this._instanceDivisor = instanced ? 1 : 0;
  19957. }
  19958. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19959. // a lot of these parameters are ignored as they are overriden by the buffer
  19960. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19961. };
  19962. // Properties
  19963. Buffer.prototype.isUpdatable = function () {
  19964. return this._updatable;
  19965. };
  19966. Buffer.prototype.getData = function () {
  19967. return this._data;
  19968. };
  19969. Buffer.prototype.getBuffer = function () {
  19970. return this._buffer;
  19971. };
  19972. Buffer.prototype.getStrideSize = function () {
  19973. return this._strideSize;
  19974. };
  19975. Buffer.prototype.getIsInstanced = function () {
  19976. return this._instanced;
  19977. };
  19978. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19979. get: function () {
  19980. return this._instanceDivisor;
  19981. },
  19982. set: function (value) {
  19983. this._instanceDivisor = value;
  19984. if (value == 0) {
  19985. this._instanced = false;
  19986. }
  19987. else {
  19988. this._instanced = true;
  19989. }
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. // Methods
  19995. Buffer.prototype.create = function (data) {
  19996. if (!data && this._buffer) {
  19997. return; // nothing to do
  19998. }
  19999. data = data || this._data;
  20000. if (!this._buffer) {
  20001. if (this._updatable) {
  20002. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20003. this._data = data;
  20004. }
  20005. else {
  20006. this._buffer = this._engine.createVertexBuffer(data);
  20007. }
  20008. }
  20009. else if (this._updatable) {
  20010. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20011. this._data = data;
  20012. }
  20013. };
  20014. Buffer.prototype._rebuild = function () {
  20015. this._buffer = null;
  20016. this.create(this._data);
  20017. };
  20018. Buffer.prototype.update = function (data) {
  20019. this.create(data);
  20020. };
  20021. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20022. if (!this._buffer) {
  20023. return;
  20024. }
  20025. if (this._updatable) {
  20026. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20027. this._data = null;
  20028. }
  20029. };
  20030. Buffer.prototype.dispose = function () {
  20031. if (!this._buffer) {
  20032. return;
  20033. }
  20034. if (this._engine._releaseBuffer(this._buffer)) {
  20035. this._buffer = null;
  20036. }
  20037. };
  20038. return Buffer;
  20039. }());
  20040. BABYLON.Buffer = Buffer;
  20041. })(BABYLON || (BABYLON = {}));
  20042. //# sourceMappingURL=babylon.buffer.js.map
  20043. var BABYLON;
  20044. (function (BABYLON) {
  20045. var VertexBuffer = (function () {
  20046. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20047. if (!stride) {
  20048. // Deduce stride from kind
  20049. switch (kind) {
  20050. case VertexBuffer.PositionKind:
  20051. stride = 3;
  20052. break;
  20053. case VertexBuffer.NormalKind:
  20054. stride = 3;
  20055. break;
  20056. case VertexBuffer.UVKind:
  20057. case VertexBuffer.UV2Kind:
  20058. case VertexBuffer.UV3Kind:
  20059. case VertexBuffer.UV4Kind:
  20060. case VertexBuffer.UV5Kind:
  20061. case VertexBuffer.UV6Kind:
  20062. stride = 2;
  20063. break;
  20064. case VertexBuffer.TangentKind:
  20065. case VertexBuffer.ColorKind:
  20066. stride = 4;
  20067. break;
  20068. case VertexBuffer.MatricesIndicesKind:
  20069. case VertexBuffer.MatricesIndicesExtraKind:
  20070. stride = 4;
  20071. break;
  20072. case VertexBuffer.MatricesWeightsKind:
  20073. case VertexBuffer.MatricesWeightsExtraKind:
  20074. stride = 4;
  20075. break;
  20076. }
  20077. }
  20078. if (data instanceof BABYLON.Buffer) {
  20079. if (!stride) {
  20080. stride = data.getStrideSize();
  20081. }
  20082. this._buffer = data;
  20083. this._ownsBuffer = false;
  20084. }
  20085. else {
  20086. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20087. this._ownsBuffer = true;
  20088. }
  20089. this._stride = stride;
  20090. this._offset = offset ? offset : 0;
  20091. this._size = size ? size : stride;
  20092. this._kind = kind;
  20093. }
  20094. VertexBuffer.prototype._rebuild = function () {
  20095. if (!this._buffer) {
  20096. return;
  20097. }
  20098. this._buffer._rebuild();
  20099. };
  20100. /**
  20101. * Returns the kind of the VertexBuffer (string).
  20102. */
  20103. VertexBuffer.prototype.getKind = function () {
  20104. return this._kind;
  20105. };
  20106. // Properties
  20107. /**
  20108. * Boolean : is the VertexBuffer updatable ?
  20109. */
  20110. VertexBuffer.prototype.isUpdatable = function () {
  20111. return this._buffer.isUpdatable();
  20112. };
  20113. /**
  20114. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20115. */
  20116. VertexBuffer.prototype.getData = function () {
  20117. return this._buffer.getData();
  20118. };
  20119. /**
  20120. * Returns the WebGLBuffer associated to the VertexBuffer.
  20121. */
  20122. VertexBuffer.prototype.getBuffer = function () {
  20123. return this._buffer.getBuffer();
  20124. };
  20125. /**
  20126. * Returns the stride of the VertexBuffer (integer).
  20127. */
  20128. VertexBuffer.prototype.getStrideSize = function () {
  20129. return this._stride;
  20130. };
  20131. /**
  20132. * Returns the offset (integer).
  20133. */
  20134. VertexBuffer.prototype.getOffset = function () {
  20135. return this._offset;
  20136. };
  20137. /**
  20138. * Returns the VertexBuffer total size (integer).
  20139. */
  20140. VertexBuffer.prototype.getSize = function () {
  20141. return this._size;
  20142. };
  20143. /**
  20144. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20145. */
  20146. VertexBuffer.prototype.getIsInstanced = function () {
  20147. return this._buffer.getIsInstanced();
  20148. };
  20149. /**
  20150. * Returns the instancing divisor, zero for non-instanced (integer).
  20151. */
  20152. VertexBuffer.prototype.getInstanceDivisor = function () {
  20153. return this._buffer.instanceDivisor;
  20154. };
  20155. // Methods
  20156. /**
  20157. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20158. * Returns the created WebGLBuffer.
  20159. */
  20160. VertexBuffer.prototype.create = function (data) {
  20161. return this._buffer.create(data);
  20162. };
  20163. /**
  20164. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20165. * Returns the updated WebGLBuffer.
  20166. */
  20167. VertexBuffer.prototype.update = function (data) {
  20168. return this._buffer.update(data);
  20169. };
  20170. /**
  20171. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20172. * Returns the directly updated WebGLBuffer.
  20173. */
  20174. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20175. return this._buffer.updateDirectly(data, offset);
  20176. };
  20177. /**
  20178. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20179. */
  20180. VertexBuffer.prototype.dispose = function () {
  20181. if (this._ownsBuffer) {
  20182. this._buffer.dispose();
  20183. }
  20184. };
  20185. Object.defineProperty(VertexBuffer, "PositionKind", {
  20186. get: function () {
  20187. return VertexBuffer._PositionKind;
  20188. },
  20189. enumerable: true,
  20190. configurable: true
  20191. });
  20192. Object.defineProperty(VertexBuffer, "NormalKind", {
  20193. get: function () {
  20194. return VertexBuffer._NormalKind;
  20195. },
  20196. enumerable: true,
  20197. configurable: true
  20198. });
  20199. Object.defineProperty(VertexBuffer, "TangentKind", {
  20200. get: function () {
  20201. return VertexBuffer._TangentKind;
  20202. },
  20203. enumerable: true,
  20204. configurable: true
  20205. });
  20206. Object.defineProperty(VertexBuffer, "UVKind", {
  20207. get: function () {
  20208. return VertexBuffer._UVKind;
  20209. },
  20210. enumerable: true,
  20211. configurable: true
  20212. });
  20213. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20214. get: function () {
  20215. return VertexBuffer._UV2Kind;
  20216. },
  20217. enumerable: true,
  20218. configurable: true
  20219. });
  20220. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20221. get: function () {
  20222. return VertexBuffer._UV3Kind;
  20223. },
  20224. enumerable: true,
  20225. configurable: true
  20226. });
  20227. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20228. get: function () {
  20229. return VertexBuffer._UV4Kind;
  20230. },
  20231. enumerable: true,
  20232. configurable: true
  20233. });
  20234. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20235. get: function () {
  20236. return VertexBuffer._UV5Kind;
  20237. },
  20238. enumerable: true,
  20239. configurable: true
  20240. });
  20241. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20242. get: function () {
  20243. return VertexBuffer._UV6Kind;
  20244. },
  20245. enumerable: true,
  20246. configurable: true
  20247. });
  20248. Object.defineProperty(VertexBuffer, "ColorKind", {
  20249. get: function () {
  20250. return VertexBuffer._ColorKind;
  20251. },
  20252. enumerable: true,
  20253. configurable: true
  20254. });
  20255. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20256. get: function () {
  20257. return VertexBuffer._MatricesIndicesKind;
  20258. },
  20259. enumerable: true,
  20260. configurable: true
  20261. });
  20262. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20263. get: function () {
  20264. return VertexBuffer._MatricesWeightsKind;
  20265. },
  20266. enumerable: true,
  20267. configurable: true
  20268. });
  20269. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20270. get: function () {
  20271. return VertexBuffer._MatricesIndicesExtraKind;
  20272. },
  20273. enumerable: true,
  20274. configurable: true
  20275. });
  20276. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20277. get: function () {
  20278. return VertexBuffer._MatricesWeightsExtraKind;
  20279. },
  20280. enumerable: true,
  20281. configurable: true
  20282. });
  20283. // Enums
  20284. VertexBuffer._PositionKind = "position";
  20285. VertexBuffer._NormalKind = "normal";
  20286. VertexBuffer._TangentKind = "tangent";
  20287. VertexBuffer._UVKind = "uv";
  20288. VertexBuffer._UV2Kind = "uv2";
  20289. VertexBuffer._UV3Kind = "uv3";
  20290. VertexBuffer._UV4Kind = "uv4";
  20291. VertexBuffer._UV5Kind = "uv5";
  20292. VertexBuffer._UV6Kind = "uv6";
  20293. VertexBuffer._ColorKind = "color";
  20294. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20295. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20296. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20297. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20298. return VertexBuffer;
  20299. }());
  20300. BABYLON.VertexBuffer = VertexBuffer;
  20301. })(BABYLON || (BABYLON = {}));
  20302. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20303. var BABYLON;
  20304. (function (BABYLON) {
  20305. var InternalTexture = (function () {
  20306. function InternalTexture(engine, dataSource) {
  20307. this.onLoadedObservable = new BABYLON.Observable();
  20308. // Private
  20309. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20310. this._references = 1;
  20311. this._engine = engine;
  20312. this._dataSource = dataSource;
  20313. this._webGLTexture = engine._createTexture();
  20314. }
  20315. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20316. get: function () {
  20317. return this._dataSource;
  20318. },
  20319. enumerable: true,
  20320. configurable: true
  20321. });
  20322. InternalTexture.prototype.incrementReferences = function () {
  20323. this._references++;
  20324. };
  20325. InternalTexture.prototype.updateSize = function (width, height) {
  20326. this.width = width;
  20327. this.height = height;
  20328. this._size = width * height;
  20329. this.baseWidth = width;
  20330. this.baseHeight = height;
  20331. };
  20332. InternalTexture.prototype._rebuild = function () {
  20333. var _this = this;
  20334. var proxy;
  20335. this.isReady = false;
  20336. this._cachedCoordinatesMode = null;
  20337. this._cachedWrapU = null;
  20338. this._cachedWrapV = null;
  20339. this._cachedAnisotropicFilteringLevel = null;
  20340. switch (this._dataSource) {
  20341. case InternalTexture.DATASOURCE_TEMP:
  20342. return;
  20343. case InternalTexture.DATASOURCE_URL:
  20344. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20345. _this.isReady = true;
  20346. }, null, this._buffer, null, this.format);
  20347. proxy._swapAndDie(this);
  20348. return;
  20349. case InternalTexture.DATASOURCE_RAW:
  20350. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20351. proxy._swapAndDie(this);
  20352. this.isReady = true;
  20353. return;
  20354. case InternalTexture.DATASOURCE_DYNAMIC:
  20355. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20356. proxy._swapAndDie(this);
  20357. // The engine will make sure to update content so no need to flag it as isReady = true
  20358. return;
  20359. case InternalTexture.DATASOURCE_RENDERTARGET:
  20360. var options = new BABYLON.RenderTargetCreationOptions();
  20361. options.generateDepthBuffer = this._generateDepthBuffer;
  20362. options.generateMipMaps = this.generateMipMaps;
  20363. options.generateStencilBuffer = this._generateStencilBuffer;
  20364. options.samplingMode = this.samplingMode;
  20365. options.type = this.type;
  20366. if (this.isCube) {
  20367. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20368. }
  20369. else {
  20370. var size = {
  20371. width: this.width,
  20372. height: this.height
  20373. };
  20374. proxy = this._engine.createRenderTargetTexture(size, options);
  20375. }
  20376. proxy._swapAndDie(this);
  20377. this.isReady = true;
  20378. return;
  20379. case InternalTexture.DATASOURCE_CUBE:
  20380. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20381. _this.isReady = true;
  20382. }, null, this.format, this._extension);
  20383. proxy._swapAndDie(this);
  20384. return;
  20385. case InternalTexture.DATASOURCE_CUBERAW:
  20386. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20387. proxy._swapAndDie(this);
  20388. this.isReady = true;
  20389. return;
  20390. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20391. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20392. proxy._swapAndDie(_this);
  20393. _this.isReady = true;
  20394. }, null, this.format, this._extension);
  20395. return;
  20396. }
  20397. };
  20398. InternalTexture.prototype._swapAndDie = function (target) {
  20399. target._webGLTexture = this._webGLTexture;
  20400. if (this._framebuffer) {
  20401. target._framebuffer = this._framebuffer;
  20402. }
  20403. if (this._depthStencilBuffer) {
  20404. target._depthStencilBuffer = this._depthStencilBuffer;
  20405. }
  20406. if (this._lodTextureHigh) {
  20407. if (target._lodTextureHigh) {
  20408. target._lodTextureHigh.dispose();
  20409. }
  20410. target._lodTextureHigh = this._lodTextureHigh;
  20411. }
  20412. if (this._lodTextureMid) {
  20413. if (target._lodTextureMid) {
  20414. target._lodTextureMid.dispose();
  20415. }
  20416. target._lodTextureMid = this._lodTextureMid;
  20417. }
  20418. if (this._lodTextureLow) {
  20419. if (target._lodTextureLow) {
  20420. target._lodTextureLow.dispose();
  20421. }
  20422. target._lodTextureLow = this._lodTextureLow;
  20423. }
  20424. var cache = this._engine.getLoadedTexturesCache();
  20425. var index = cache.indexOf(this);
  20426. if (index !== -1) {
  20427. cache.splice(index, 1);
  20428. }
  20429. };
  20430. InternalTexture.prototype.dispose = function () {
  20431. if (!this._webGLTexture) {
  20432. return;
  20433. }
  20434. this._references--;
  20435. if (this._references === 0) {
  20436. this._engine._releaseTexture(this);
  20437. this._webGLTexture = null;
  20438. }
  20439. };
  20440. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20441. InternalTexture.DATASOURCE_URL = 1;
  20442. InternalTexture.DATASOURCE_TEMP = 2;
  20443. InternalTexture.DATASOURCE_RAW = 3;
  20444. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20445. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20446. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20447. InternalTexture.DATASOURCE_CUBE = 7;
  20448. InternalTexture.DATASOURCE_CUBERAW = 8;
  20449. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20450. return InternalTexture;
  20451. }());
  20452. BABYLON.InternalTexture = InternalTexture;
  20453. })(BABYLON || (BABYLON = {}));
  20454. //# sourceMappingURL=babylon.internalTexture.js.map
  20455. var BABYLON;
  20456. (function (BABYLON) {
  20457. var BaseTexture = (function () {
  20458. function BaseTexture(scene) {
  20459. this._hasAlpha = false;
  20460. this.getAlphaFromRGB = false;
  20461. this.level = 1;
  20462. this.coordinatesIndex = 0;
  20463. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20464. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20465. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20466. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20467. this.isCube = false;
  20468. this.gammaSpace = true;
  20469. this.invertZ = false;
  20470. this.lodLevelInAlpha = false;
  20471. this.lodGenerationOffset = 0.0;
  20472. this.lodGenerationScale = 0.8;
  20473. this.isRenderTarget = false;
  20474. this.animations = new Array();
  20475. /**
  20476. * An event triggered when the texture is disposed.
  20477. * @type {BABYLON.Observable}
  20478. */
  20479. this.onDisposeObservable = new BABYLON.Observable();
  20480. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20481. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20482. this._scene.textures.push(this);
  20483. this._uid = null;
  20484. }
  20485. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20486. get: function () {
  20487. return this._hasAlpha;
  20488. },
  20489. set: function (value) {
  20490. if (this._hasAlpha === value) {
  20491. return;
  20492. }
  20493. this._hasAlpha = value;
  20494. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20495. },
  20496. enumerable: true,
  20497. configurable: true
  20498. });
  20499. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20500. get: function () {
  20501. return this._coordinatesMode;
  20502. },
  20503. set: function (value) {
  20504. if (this._coordinatesMode === value) {
  20505. return;
  20506. }
  20507. this._coordinatesMode = value;
  20508. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20509. },
  20510. enumerable: true,
  20511. configurable: true
  20512. });
  20513. Object.defineProperty(BaseTexture.prototype, "uid", {
  20514. get: function () {
  20515. if (!this._uid) {
  20516. this._uid = BABYLON.Tools.RandomId();
  20517. }
  20518. return this._uid;
  20519. },
  20520. enumerable: true,
  20521. configurable: true
  20522. });
  20523. BaseTexture.prototype.toString = function () {
  20524. return this.name;
  20525. };
  20526. BaseTexture.prototype.getClassName = function () {
  20527. return "BaseTexture";
  20528. };
  20529. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20530. set: function (callback) {
  20531. if (this._onDisposeObserver) {
  20532. this.onDisposeObservable.remove(this._onDisposeObserver);
  20533. }
  20534. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20535. },
  20536. enumerable: true,
  20537. configurable: true
  20538. });
  20539. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20540. get: function () {
  20541. return true;
  20542. },
  20543. enumerable: true,
  20544. configurable: true
  20545. });
  20546. BaseTexture.prototype.getScene = function () {
  20547. return this._scene;
  20548. };
  20549. BaseTexture.prototype.getTextureMatrix = function () {
  20550. return null;
  20551. };
  20552. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20553. return null;
  20554. };
  20555. BaseTexture.prototype.getInternalTexture = function () {
  20556. return this._texture;
  20557. };
  20558. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20559. return !this.isBlocking || this.isReady();
  20560. };
  20561. BaseTexture.prototype.isReady = function () {
  20562. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20563. this.delayLoad();
  20564. return false;
  20565. }
  20566. if (this._texture) {
  20567. return this._texture.isReady;
  20568. }
  20569. return false;
  20570. };
  20571. BaseTexture.prototype.getSize = function () {
  20572. if (this._texture.width) {
  20573. return new BABYLON.Size(this._texture.width, this._texture.height);
  20574. }
  20575. if (this._texture._size) {
  20576. return new BABYLON.Size(this._texture._size, this._texture._size);
  20577. }
  20578. return BABYLON.Size.Zero();
  20579. };
  20580. BaseTexture.prototype.getBaseSize = function () {
  20581. if (!this.isReady() || !this._texture)
  20582. return BABYLON.Size.Zero();
  20583. if (this._texture._size) {
  20584. return new BABYLON.Size(this._texture._size, this._texture._size);
  20585. }
  20586. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20587. };
  20588. BaseTexture.prototype.scale = function (ratio) {
  20589. };
  20590. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20591. get: function () {
  20592. return false;
  20593. },
  20594. enumerable: true,
  20595. configurable: true
  20596. });
  20597. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20598. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20599. for (var index = 0; index < texturesCache.length; index++) {
  20600. var texturesCacheEntry = texturesCache[index];
  20601. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20602. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20603. texturesCacheEntry.incrementReferences();
  20604. return texturesCacheEntry;
  20605. }
  20606. }
  20607. }
  20608. return null;
  20609. };
  20610. BaseTexture.prototype._rebuild = function () {
  20611. };
  20612. BaseTexture.prototype.delayLoad = function () {
  20613. };
  20614. BaseTexture.prototype.clone = function () {
  20615. return null;
  20616. };
  20617. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20618. get: function () {
  20619. if (!this._texture) {
  20620. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20621. }
  20622. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20623. },
  20624. enumerable: true,
  20625. configurable: true
  20626. });
  20627. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20628. get: function () {
  20629. if (!this._texture) {
  20630. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20631. }
  20632. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20633. },
  20634. enumerable: true,
  20635. configurable: true
  20636. });
  20637. BaseTexture.prototype.readPixels = function (faceIndex) {
  20638. if (faceIndex === void 0) { faceIndex = 0; }
  20639. if (!this._texture) {
  20640. return null;
  20641. }
  20642. var size = this.getSize();
  20643. var engine = this.getScene().getEngine();
  20644. if (this._texture.isCube) {
  20645. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20646. }
  20647. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20648. };
  20649. BaseTexture.prototype.releaseInternalTexture = function () {
  20650. if (this._texture) {
  20651. this._texture.dispose();
  20652. this._texture = null;
  20653. }
  20654. };
  20655. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20656. get: function () {
  20657. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20658. return null;
  20659. }
  20660. if (!this._texture._sphericalPolynomial) {
  20661. this._texture._sphericalPolynomial =
  20662. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20663. }
  20664. return this._texture._sphericalPolynomial;
  20665. },
  20666. set: function (value) {
  20667. if (this._texture) {
  20668. this._texture._sphericalPolynomial = value;
  20669. }
  20670. },
  20671. enumerable: true,
  20672. configurable: true
  20673. });
  20674. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20675. get: function () {
  20676. if (this._texture) {
  20677. return this._texture._lodTextureHigh;
  20678. }
  20679. return null;
  20680. },
  20681. enumerable: true,
  20682. configurable: true
  20683. });
  20684. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20685. get: function () {
  20686. if (this._texture) {
  20687. return this._texture._lodTextureMid;
  20688. }
  20689. return null;
  20690. },
  20691. enumerable: true,
  20692. configurable: true
  20693. });
  20694. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20695. get: function () {
  20696. if (this._texture) {
  20697. return this._texture._lodTextureLow;
  20698. }
  20699. return null;
  20700. },
  20701. enumerable: true,
  20702. configurable: true
  20703. });
  20704. BaseTexture.prototype.dispose = function () {
  20705. // Animations
  20706. this.getScene().stopAnimation(this);
  20707. // Remove from scene
  20708. this._scene._removePendingData(this);
  20709. var index = this._scene.textures.indexOf(this);
  20710. if (index >= 0) {
  20711. this._scene.textures.splice(index, 1);
  20712. }
  20713. if (this._texture === undefined) {
  20714. return;
  20715. }
  20716. // Release
  20717. this.releaseInternalTexture();
  20718. // Callback
  20719. this.onDisposeObservable.notifyObservers(this);
  20720. this.onDisposeObservable.clear();
  20721. };
  20722. BaseTexture.prototype.serialize = function () {
  20723. if (!this.name) {
  20724. return null;
  20725. }
  20726. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20727. // Animations
  20728. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20729. return serializationObject;
  20730. };
  20731. BaseTexture.WhenAllReady = function (textures, callback) {
  20732. var numRemaining = textures.length;
  20733. if (numRemaining === 0) {
  20734. callback();
  20735. return;
  20736. }
  20737. var _loop_1 = function () {
  20738. texture = textures[i];
  20739. if (texture.isReady()) {
  20740. if (--numRemaining === 0) {
  20741. callback();
  20742. }
  20743. }
  20744. else {
  20745. onLoadObservable = texture.onLoadObservable;
  20746. var onLoadCallback_1 = function () {
  20747. onLoadObservable.removeCallback(onLoadCallback_1);
  20748. if (--numRemaining === 0) {
  20749. callback();
  20750. }
  20751. };
  20752. onLoadObservable.add(onLoadCallback_1);
  20753. }
  20754. };
  20755. var texture, onLoadObservable;
  20756. for (var i = 0; i < textures.length; i++) {
  20757. _loop_1();
  20758. }
  20759. };
  20760. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20761. __decorate([
  20762. BABYLON.serialize()
  20763. ], BaseTexture.prototype, "name", void 0);
  20764. __decorate([
  20765. BABYLON.serialize("hasAlpha")
  20766. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20767. __decorate([
  20768. BABYLON.serialize()
  20769. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20770. __decorate([
  20771. BABYLON.serialize()
  20772. ], BaseTexture.prototype, "level", void 0);
  20773. __decorate([
  20774. BABYLON.serialize()
  20775. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20776. __decorate([
  20777. BABYLON.serialize("coordinatesMode")
  20778. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20779. __decorate([
  20780. BABYLON.serialize()
  20781. ], BaseTexture.prototype, "wrapU", void 0);
  20782. __decorate([
  20783. BABYLON.serialize()
  20784. ], BaseTexture.prototype, "wrapV", void 0);
  20785. __decorate([
  20786. BABYLON.serialize()
  20787. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20788. __decorate([
  20789. BABYLON.serialize()
  20790. ], BaseTexture.prototype, "isCube", void 0);
  20791. __decorate([
  20792. BABYLON.serialize()
  20793. ], BaseTexture.prototype, "gammaSpace", void 0);
  20794. __decorate([
  20795. BABYLON.serialize()
  20796. ], BaseTexture.prototype, "invertZ", void 0);
  20797. __decorate([
  20798. BABYLON.serialize()
  20799. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20800. __decorate([
  20801. BABYLON.serialize()
  20802. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20803. __decorate([
  20804. BABYLON.serialize()
  20805. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20806. __decorate([
  20807. BABYLON.serialize()
  20808. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20809. return BaseTexture;
  20810. }());
  20811. BABYLON.BaseTexture = BaseTexture;
  20812. })(BABYLON || (BABYLON = {}));
  20813. //# sourceMappingURL=babylon.baseTexture.js.map
  20814. var BABYLON;
  20815. (function (BABYLON) {
  20816. var Texture = (function (_super) {
  20817. __extends(Texture, _super);
  20818. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20819. if (noMipmap === void 0) { noMipmap = false; }
  20820. if (invertY === void 0) { invertY = true; }
  20821. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20822. if (onLoad === void 0) { onLoad = null; }
  20823. if (onError === void 0) { onError = null; }
  20824. if (buffer === void 0) { buffer = null; }
  20825. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20826. var _this = _super.call(this, scene) || this;
  20827. _this.uOffset = 0;
  20828. _this.vOffset = 0;
  20829. _this.uScale = 1.0;
  20830. _this.vScale = 1.0;
  20831. _this.uAng = 0;
  20832. _this.vAng = 0;
  20833. _this.wAng = 0;
  20834. _this._isBlocking = true;
  20835. _this.name = url;
  20836. _this.url = url;
  20837. _this._noMipmap = noMipmap;
  20838. _this._invertY = invertY;
  20839. _this._samplingMode = samplingMode;
  20840. _this._buffer = buffer;
  20841. _this._deleteBuffer = deleteBuffer;
  20842. _this._format = format;
  20843. scene = _this.getScene();
  20844. var load = function () {
  20845. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20846. _this.onLoadObservable.notifyObservers(_this);
  20847. }
  20848. if (onLoad) {
  20849. onLoad();
  20850. }
  20851. if (!_this.isBlocking) {
  20852. scene.resetCachedMaterial();
  20853. }
  20854. };
  20855. if (!url) {
  20856. _this._delayedOnLoad = load;
  20857. _this._delayedOnError = onError;
  20858. return _this;
  20859. }
  20860. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20861. if (!_this._texture) {
  20862. if (!scene.useDelayedTextureLoading) {
  20863. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20864. if (deleteBuffer) {
  20865. delete _this._buffer;
  20866. }
  20867. }
  20868. else {
  20869. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20870. _this._delayedOnLoad = load;
  20871. _this._delayedOnError = onError;
  20872. }
  20873. }
  20874. else {
  20875. if (_this._texture.isReady) {
  20876. BABYLON.Tools.SetImmediate(function () { return load(); });
  20877. }
  20878. else {
  20879. _this._texture.onLoadedObservable.add(load);
  20880. }
  20881. }
  20882. return _this;
  20883. }
  20884. Object.defineProperty(Texture.prototype, "noMipmap", {
  20885. get: function () {
  20886. return this._noMipmap;
  20887. },
  20888. enumerable: true,
  20889. configurable: true
  20890. });
  20891. Object.defineProperty(Texture.prototype, "isBlocking", {
  20892. get: function () {
  20893. return this._isBlocking;
  20894. },
  20895. set: function (value) {
  20896. this._isBlocking = value;
  20897. },
  20898. enumerable: true,
  20899. configurable: true
  20900. });
  20901. Object.defineProperty(Texture.prototype, "samplingMode", {
  20902. get: function () {
  20903. return this._samplingMode;
  20904. },
  20905. enumerable: true,
  20906. configurable: true
  20907. });
  20908. Texture.prototype.updateURL = function (url) {
  20909. this.url = url;
  20910. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20911. this.delayLoad();
  20912. };
  20913. Texture.prototype.delayLoad = function () {
  20914. var _this = this;
  20915. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20916. return;
  20917. }
  20918. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20919. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20920. if (!this._texture) {
  20921. 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);
  20922. if (this._deleteBuffer) {
  20923. delete this._buffer;
  20924. }
  20925. }
  20926. else {
  20927. if (this._texture.isReady) {
  20928. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20929. }
  20930. else {
  20931. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20932. }
  20933. }
  20934. };
  20935. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20936. if (!this._texture) {
  20937. return;
  20938. }
  20939. this._samplingMode = samplingMode;
  20940. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20941. };
  20942. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20943. x *= this.uScale;
  20944. y *= this.vScale;
  20945. x -= 0.5 * this.uScale;
  20946. y -= 0.5 * this.vScale;
  20947. z -= 0.5;
  20948. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20949. t.x += 0.5 * this.uScale + this.uOffset;
  20950. t.y += 0.5 * this.vScale + this.vOffset;
  20951. t.z += 0.5;
  20952. };
  20953. Texture.prototype.getTextureMatrix = function () {
  20954. var _this = this;
  20955. if (this.uOffset === this._cachedUOffset &&
  20956. this.vOffset === this._cachedVOffset &&
  20957. this.uScale === this._cachedUScale &&
  20958. this.vScale === this._cachedVScale &&
  20959. this.uAng === this._cachedUAng &&
  20960. this.vAng === this._cachedVAng &&
  20961. this.wAng === this._cachedWAng) {
  20962. return this._cachedTextureMatrix;
  20963. }
  20964. this._cachedUOffset = this.uOffset;
  20965. this._cachedVOffset = this.vOffset;
  20966. this._cachedUScale = this.uScale;
  20967. this._cachedVScale = this.vScale;
  20968. this._cachedUAng = this.uAng;
  20969. this._cachedVAng = this.vAng;
  20970. this._cachedWAng = this.wAng;
  20971. if (!this._cachedTextureMatrix) {
  20972. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20973. this._rowGenerationMatrix = new BABYLON.Matrix();
  20974. this._t0 = BABYLON.Vector3.Zero();
  20975. this._t1 = BABYLON.Vector3.Zero();
  20976. this._t2 = BABYLON.Vector3.Zero();
  20977. }
  20978. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20979. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20980. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20981. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20982. this._t1.subtractInPlace(this._t0);
  20983. this._t2.subtractInPlace(this._t0);
  20984. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20985. this._cachedTextureMatrix.m[0] = this._t1.x;
  20986. this._cachedTextureMatrix.m[1] = this._t1.y;
  20987. this._cachedTextureMatrix.m[2] = this._t1.z;
  20988. this._cachedTextureMatrix.m[4] = this._t2.x;
  20989. this._cachedTextureMatrix.m[5] = this._t2.y;
  20990. this._cachedTextureMatrix.m[6] = this._t2.z;
  20991. this._cachedTextureMatrix.m[8] = this._t0.x;
  20992. this._cachedTextureMatrix.m[9] = this._t0.y;
  20993. this._cachedTextureMatrix.m[10] = this._t0.z;
  20994. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20995. return mat.hasTexture(_this);
  20996. });
  20997. return this._cachedTextureMatrix;
  20998. };
  20999. Texture.prototype.getReflectionTextureMatrix = function () {
  21000. var _this = this;
  21001. var scene = this.getScene();
  21002. if (this.uOffset === this._cachedUOffset &&
  21003. this.vOffset === this._cachedVOffset &&
  21004. this.uScale === this._cachedUScale &&
  21005. this.vScale === this._cachedVScale &&
  21006. this.coordinatesMode === this._cachedCoordinatesMode) {
  21007. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21008. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21009. return this._cachedTextureMatrix;
  21010. }
  21011. }
  21012. else {
  21013. return this._cachedTextureMatrix;
  21014. }
  21015. }
  21016. if (!this._cachedTextureMatrix) {
  21017. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21018. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21019. }
  21020. this._cachedUOffset = this.uOffset;
  21021. this._cachedVOffset = this.vOffset;
  21022. this._cachedUScale = this.uScale;
  21023. this._cachedVScale = this.vScale;
  21024. this._cachedCoordinatesMode = this.coordinatesMode;
  21025. switch (this.coordinatesMode) {
  21026. case Texture.PLANAR_MODE:
  21027. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21028. this._cachedTextureMatrix[0] = this.uScale;
  21029. this._cachedTextureMatrix[5] = this.vScale;
  21030. this._cachedTextureMatrix[12] = this.uOffset;
  21031. this._cachedTextureMatrix[13] = this.vOffset;
  21032. break;
  21033. case Texture.PROJECTION_MODE:
  21034. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21035. this._projectionModeMatrix.m[0] = 0.5;
  21036. this._projectionModeMatrix.m[5] = -0.5;
  21037. this._projectionModeMatrix.m[10] = 0.0;
  21038. this._projectionModeMatrix.m[12] = 0.5;
  21039. this._projectionModeMatrix.m[13] = 0.5;
  21040. this._projectionModeMatrix.m[14] = 1.0;
  21041. this._projectionModeMatrix.m[15] = 1.0;
  21042. var projectionMatrix = scene.getProjectionMatrix();
  21043. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  21044. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21045. break;
  21046. default:
  21047. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21048. break;
  21049. }
  21050. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21051. return (mat.getActiveTextures().indexOf(_this) !== -1);
  21052. });
  21053. return this._cachedTextureMatrix;
  21054. };
  21055. Texture.prototype.clone = function () {
  21056. var _this = this;
  21057. return BABYLON.SerializationHelper.Clone(function () {
  21058. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21059. }, this);
  21060. };
  21061. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21062. get: function () {
  21063. if (!this._onLoadObservable) {
  21064. this._onLoadObservable = new BABYLON.Observable();
  21065. }
  21066. return this._onLoadObservable;
  21067. },
  21068. enumerable: true,
  21069. configurable: true
  21070. });
  21071. Texture.prototype.serialize = function () {
  21072. var serializationObject = _super.prototype.serialize.call(this);
  21073. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  21074. serializationObject.base64String = this._buffer;
  21075. serializationObject.name = serializationObject.name.replace("data:", "");
  21076. }
  21077. return serializationObject;
  21078. };
  21079. Texture.prototype.getClassName = function () {
  21080. return "Texture";
  21081. };
  21082. Texture.prototype.dispose = function () {
  21083. _super.prototype.dispose.call(this);
  21084. if (this.onLoadObservable) {
  21085. this.onLoadObservable.clear();
  21086. this._onLoadObservable = null;
  21087. }
  21088. this._delayedOnLoad = null;
  21089. this._delayedOnError = null;
  21090. };
  21091. // Statics
  21092. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21093. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21094. if (onLoad === void 0) { onLoad = null; }
  21095. if (onError === void 0) { onError = null; }
  21096. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21097. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21098. };
  21099. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21100. if (parsedTexture.customType) {
  21101. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21102. // Update Sampling Mode
  21103. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21104. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21105. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21106. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21107. }
  21108. }
  21109. return parsedCustomTexture;
  21110. }
  21111. if (parsedTexture.isCube) {
  21112. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21113. }
  21114. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21115. return null;
  21116. }
  21117. var texture = BABYLON.SerializationHelper.Parse(function () {
  21118. if (parsedTexture.mirrorPlane) {
  21119. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21120. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21121. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21122. return mirrorTexture;
  21123. }
  21124. else if (parsedTexture.isRenderTarget) {
  21125. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21126. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21127. return renderTargetTexture;
  21128. }
  21129. else {
  21130. var texture;
  21131. if (parsedTexture.base64String) {
  21132. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21133. }
  21134. else {
  21135. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21136. }
  21137. return texture;
  21138. }
  21139. }, parsedTexture, scene);
  21140. // Update Sampling Mode
  21141. if (parsedTexture.samplingMode) {
  21142. var sampling = parsedTexture.samplingMode;
  21143. if (texture._samplingMode !== sampling) {
  21144. texture.updateSamplingMode(sampling);
  21145. }
  21146. }
  21147. // Animations
  21148. if (parsedTexture.animations) {
  21149. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21150. var parsedAnimation = parsedTexture.animations[animationIndex];
  21151. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21152. }
  21153. }
  21154. return texture;
  21155. };
  21156. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21157. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21158. if (noMipmap === void 0) { noMipmap = false; }
  21159. if (invertY === void 0) { invertY = true; }
  21160. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21161. if (onLoad === void 0) { onLoad = null; }
  21162. if (onError === void 0) { onError = null; }
  21163. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21164. if (name.substr(0, 5) !== "data:") {
  21165. name = "data:" + name;
  21166. }
  21167. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21168. };
  21169. // Constants
  21170. Texture.NEAREST_SAMPLINGMODE = 1;
  21171. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21172. Texture.BILINEAR_SAMPLINGMODE = 2;
  21173. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21174. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21175. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21176. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21177. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21178. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21179. Texture.NEAREST_LINEAR = 7;
  21180. Texture.NEAREST_NEAREST = 8;
  21181. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21182. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21183. Texture.LINEAR_LINEAR = 11;
  21184. Texture.LINEAR_NEAREST = 12;
  21185. Texture.EXPLICIT_MODE = 0;
  21186. Texture.SPHERICAL_MODE = 1;
  21187. Texture.PLANAR_MODE = 2;
  21188. Texture.CUBIC_MODE = 3;
  21189. Texture.PROJECTION_MODE = 4;
  21190. Texture.SKYBOX_MODE = 5;
  21191. Texture.INVCUBIC_MODE = 6;
  21192. Texture.EQUIRECTANGULAR_MODE = 7;
  21193. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21194. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21195. Texture.CLAMP_ADDRESSMODE = 0;
  21196. Texture.WRAP_ADDRESSMODE = 1;
  21197. Texture.MIRROR_ADDRESSMODE = 2;
  21198. __decorate([
  21199. BABYLON.serialize()
  21200. ], Texture.prototype, "url", void 0);
  21201. __decorate([
  21202. BABYLON.serialize()
  21203. ], Texture.prototype, "uOffset", void 0);
  21204. __decorate([
  21205. BABYLON.serialize()
  21206. ], Texture.prototype, "vOffset", void 0);
  21207. __decorate([
  21208. BABYLON.serialize()
  21209. ], Texture.prototype, "uScale", void 0);
  21210. __decorate([
  21211. BABYLON.serialize()
  21212. ], Texture.prototype, "vScale", void 0);
  21213. __decorate([
  21214. BABYLON.serialize()
  21215. ], Texture.prototype, "uAng", void 0);
  21216. __decorate([
  21217. BABYLON.serialize()
  21218. ], Texture.prototype, "vAng", void 0);
  21219. __decorate([
  21220. BABYLON.serialize()
  21221. ], Texture.prototype, "wAng", void 0);
  21222. __decorate([
  21223. BABYLON.serialize()
  21224. ], Texture.prototype, "isBlocking", null);
  21225. return Texture;
  21226. }(BABYLON.BaseTexture));
  21227. BABYLON.Texture = Texture;
  21228. })(BABYLON || (BABYLON = {}));
  21229. //# sourceMappingURL=babylon.texture.js.map
  21230. var BABYLON;
  21231. (function (BABYLON) {
  21232. var _InstancesBatch = (function () {
  21233. function _InstancesBatch() {
  21234. this.mustReturn = false;
  21235. this.visibleInstances = new Array();
  21236. this.renderSelf = new Array();
  21237. }
  21238. return _InstancesBatch;
  21239. }());
  21240. BABYLON._InstancesBatch = _InstancesBatch;
  21241. var Mesh = (function (_super) {
  21242. __extends(Mesh, _super);
  21243. /**
  21244. * @constructor
  21245. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21246. * @param {Scene} scene The scene to add this mesh to.
  21247. * @param {Node} parent The parent of this mesh, if it has one
  21248. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21249. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21250. * When false, achieved by calling a clone(), also passing False.
  21251. * This will make creation of children, recursive.
  21252. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21253. */
  21254. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21255. if (parent === void 0) { parent = null; }
  21256. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21257. var _this = _super.call(this, name, scene) || this;
  21258. // Events
  21259. /**
  21260. * An event triggered before rendering the mesh
  21261. * @type {BABYLON.Observable}
  21262. */
  21263. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21264. /**
  21265. * An event triggered after rendering the mesh
  21266. * @type {BABYLON.Observable}
  21267. */
  21268. _this.onAfterRenderObservable = new BABYLON.Observable();
  21269. /**
  21270. * An event triggered before drawing the mesh
  21271. * @type {BABYLON.Observable}
  21272. */
  21273. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21274. // Members
  21275. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21276. _this.instances = new Array();
  21277. _this._LODLevels = new Array();
  21278. _this._visibleInstances = {};
  21279. _this._renderIdForInstances = new Array();
  21280. _this._batchCache = new _InstancesBatch();
  21281. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21282. _this._sideOrientation = Mesh._DEFAULTSIDE;
  21283. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21284. // Will be used to save a source mesh reference, If any
  21285. _this._source = null;
  21286. if (source) {
  21287. // Source mesh
  21288. _this._source = source;
  21289. // Geometry
  21290. if (source._geometry) {
  21291. source._geometry.applyToMesh(_this);
  21292. }
  21293. // Deep copy
  21294. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21295. // Parent
  21296. _this.parent = source.parent;
  21297. // Pivot
  21298. _this.setPivotMatrix(source.getPivotMatrix());
  21299. _this.id = name + "." + source.id;
  21300. // Material
  21301. _this.material = source.material;
  21302. var index;
  21303. if (!doNotCloneChildren) {
  21304. // Children
  21305. for (index = 0; index < scene.meshes.length; index++) {
  21306. var mesh = scene.meshes[index];
  21307. if (mesh.parent === source) {
  21308. // doNotCloneChildren is always going to be False
  21309. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21310. }
  21311. }
  21312. }
  21313. // Physics clone
  21314. var physicsEngine = _this.getScene().getPhysicsEngine();
  21315. if (clonePhysicsImpostor && physicsEngine) {
  21316. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21317. if (impostor) {
  21318. _this.physicsImpostor = impostor.clone(_this);
  21319. }
  21320. }
  21321. // Particles
  21322. for (index = 0; index < scene.particleSystems.length; index++) {
  21323. var system = scene.particleSystems[index];
  21324. if (system.emitter === source) {
  21325. system.clone(system.name, _this);
  21326. }
  21327. }
  21328. _this.computeWorldMatrix(true);
  21329. }
  21330. // Parent
  21331. if (parent !== null) {
  21332. _this.parent = parent;
  21333. }
  21334. return _this;
  21335. }
  21336. Object.defineProperty(Mesh, "FRONTSIDE", {
  21337. /**
  21338. * Mesh side orientation : usually the external or front surface
  21339. */
  21340. get: function () {
  21341. return Mesh._FRONTSIDE;
  21342. },
  21343. enumerable: true,
  21344. configurable: true
  21345. });
  21346. Object.defineProperty(Mesh, "BACKSIDE", {
  21347. /**
  21348. * Mesh side orientation : usually the internal or back surface
  21349. */
  21350. get: function () {
  21351. return Mesh._BACKSIDE;
  21352. },
  21353. enumerable: true,
  21354. configurable: true
  21355. });
  21356. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21357. /**
  21358. * Mesh side orientation : both internal and external or front and back surfaces
  21359. */
  21360. get: function () {
  21361. return Mesh._DOUBLESIDE;
  21362. },
  21363. enumerable: true,
  21364. configurable: true
  21365. });
  21366. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21367. /**
  21368. * Mesh side orientation : by default, `FRONTSIDE`
  21369. */
  21370. get: function () {
  21371. return Mesh._DEFAULTSIDE;
  21372. },
  21373. enumerable: true,
  21374. configurable: true
  21375. });
  21376. Object.defineProperty(Mesh, "NO_CAP", {
  21377. /**
  21378. * Mesh cap setting : no cap
  21379. */
  21380. get: function () {
  21381. return Mesh._NO_CAP;
  21382. },
  21383. enumerable: true,
  21384. configurable: true
  21385. });
  21386. Object.defineProperty(Mesh, "CAP_START", {
  21387. /**
  21388. * Mesh cap setting : one cap at the beginning of the mesh
  21389. */
  21390. get: function () {
  21391. return Mesh._CAP_START;
  21392. },
  21393. enumerable: true,
  21394. configurable: true
  21395. });
  21396. Object.defineProperty(Mesh, "CAP_END", {
  21397. /**
  21398. * Mesh cap setting : one cap at the end of the mesh
  21399. */
  21400. get: function () {
  21401. return Mesh._CAP_END;
  21402. },
  21403. enumerable: true,
  21404. configurable: true
  21405. });
  21406. Object.defineProperty(Mesh, "CAP_ALL", {
  21407. /**
  21408. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21409. */
  21410. get: function () {
  21411. return Mesh._CAP_ALL;
  21412. },
  21413. enumerable: true,
  21414. configurable: true
  21415. });
  21416. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21417. set: function (callback) {
  21418. if (this._onBeforeDrawObserver) {
  21419. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21420. }
  21421. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21422. },
  21423. enumerable: true,
  21424. configurable: true
  21425. });
  21426. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21427. get: function () {
  21428. return this._morphTargetManager;
  21429. },
  21430. set: function (value) {
  21431. if (this._morphTargetManager === value) {
  21432. return;
  21433. }
  21434. this._morphTargetManager = value;
  21435. this._syncGeometryWithMorphTargetManager();
  21436. },
  21437. enumerable: true,
  21438. configurable: true
  21439. });
  21440. Object.defineProperty(Mesh.prototype, "source", {
  21441. get: function () {
  21442. return this._source;
  21443. },
  21444. enumerable: true,
  21445. configurable: true
  21446. });
  21447. // Methods
  21448. /**
  21449. * Returns the string "Mesh".
  21450. */
  21451. Mesh.prototype.getClassName = function () {
  21452. return "Mesh";
  21453. };
  21454. /**
  21455. * Returns a string.
  21456. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21457. */
  21458. Mesh.prototype.toString = function (fullDetails) {
  21459. var ret = _super.prototype.toString.call(this, fullDetails);
  21460. ret += ", n vertices: " + this.getTotalVertices();
  21461. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21462. if (this.animations) {
  21463. for (var i = 0; i < this.animations.length; i++) {
  21464. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21465. }
  21466. }
  21467. if (fullDetails) {
  21468. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21469. }
  21470. return ret;
  21471. };
  21472. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21473. /**
  21474. * True if the mesh has some Levels Of Details (LOD).
  21475. * Returns a boolean.
  21476. */
  21477. get: function () {
  21478. return this._LODLevels.length > 0;
  21479. },
  21480. enumerable: true,
  21481. configurable: true
  21482. });
  21483. Mesh.prototype._sortLODLevels = function () {
  21484. this._LODLevels.sort(function (a, b) {
  21485. if (a.distance < b.distance) {
  21486. return 1;
  21487. }
  21488. if (a.distance > b.distance) {
  21489. return -1;
  21490. }
  21491. return 0;
  21492. });
  21493. };
  21494. /**
  21495. * Add a mesh as LOD level triggered at the given distance.
  21496. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21497. * @param {number} distance The distance from the center of the object to show this level
  21498. * @param {Mesh} mesh The mesh to be added as LOD level
  21499. * @return {Mesh} This mesh (for chaining)
  21500. */
  21501. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21502. if (mesh && mesh._masterMesh) {
  21503. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21504. return this;
  21505. }
  21506. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21507. this._LODLevels.push(level);
  21508. if (mesh) {
  21509. mesh._masterMesh = this;
  21510. }
  21511. this._sortLODLevels();
  21512. return this;
  21513. };
  21514. /**
  21515. * Returns the LOD level mesh at the passed distance or null if not found.
  21516. * It is related to the method `addLODLevel(distance, mesh)`.
  21517. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21518. * Returns an object Mesh or `null`.
  21519. */
  21520. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21521. for (var index = 0; index < this._LODLevels.length; index++) {
  21522. var level = this._LODLevels[index];
  21523. if (level.distance === distance) {
  21524. return level.mesh;
  21525. }
  21526. }
  21527. return null;
  21528. };
  21529. /**
  21530. * Remove a mesh from the LOD array
  21531. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21532. * @param {Mesh} mesh The mesh to be removed.
  21533. * @return {Mesh} This mesh (for chaining)
  21534. */
  21535. Mesh.prototype.removeLODLevel = function (mesh) {
  21536. for (var index = 0; index < this._LODLevels.length; index++) {
  21537. if (this._LODLevels[index].mesh === mesh) {
  21538. this._LODLevels.splice(index, 1);
  21539. if (mesh) {
  21540. mesh._masterMesh = null;
  21541. }
  21542. }
  21543. }
  21544. this._sortLODLevels();
  21545. return this;
  21546. };
  21547. /**
  21548. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21549. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21550. */
  21551. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21552. if (!this._LODLevels || this._LODLevels.length === 0) {
  21553. return this;
  21554. }
  21555. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21556. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21557. if (this.onLODLevelSelection) {
  21558. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21559. }
  21560. return this;
  21561. }
  21562. for (var index = 0; index < this._LODLevels.length; index++) {
  21563. var level = this._LODLevels[index];
  21564. if (level.distance < distanceToCamera) {
  21565. if (level.mesh) {
  21566. level.mesh._preActivate();
  21567. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21568. }
  21569. if (this.onLODLevelSelection) {
  21570. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21571. }
  21572. return level.mesh;
  21573. }
  21574. }
  21575. if (this.onLODLevelSelection) {
  21576. this.onLODLevelSelection(distanceToCamera, this, this);
  21577. }
  21578. return this;
  21579. };
  21580. Object.defineProperty(Mesh.prototype, "geometry", {
  21581. /**
  21582. * Returns the mesh internal Geometry object.
  21583. */
  21584. get: function () {
  21585. return this._geometry;
  21586. },
  21587. enumerable: true,
  21588. configurable: true
  21589. });
  21590. /**
  21591. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21592. */
  21593. Mesh.prototype.getTotalVertices = function () {
  21594. if (!this._geometry) {
  21595. return 0;
  21596. }
  21597. return this._geometry.getTotalVertices();
  21598. };
  21599. /**
  21600. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21601. * 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.
  21602. * You can force the copy with forceCopy === true
  21603. * Returns null if the mesh has no geometry or no vertex buffer.
  21604. * Possible `kind` values :
  21605. * - BABYLON.VertexBuffer.PositionKind
  21606. * - BABYLON.VertexBuffer.UVKind
  21607. * - BABYLON.VertexBuffer.UV2Kind
  21608. * - BABYLON.VertexBuffer.UV3Kind
  21609. * - BABYLON.VertexBuffer.UV4Kind
  21610. * - BABYLON.VertexBuffer.UV5Kind
  21611. * - BABYLON.VertexBuffer.UV6Kind
  21612. * - BABYLON.VertexBuffer.ColorKind
  21613. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21614. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21615. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21616. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21617. */
  21618. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21619. if (!this._geometry) {
  21620. return null;
  21621. }
  21622. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21623. };
  21624. /**
  21625. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21626. * Returns `undefined` if the mesh has no geometry.
  21627. * Possible `kind` values :
  21628. * - BABYLON.VertexBuffer.PositionKind
  21629. * - BABYLON.VertexBuffer.UVKind
  21630. * - BABYLON.VertexBuffer.UV2Kind
  21631. * - BABYLON.VertexBuffer.UV3Kind
  21632. * - BABYLON.VertexBuffer.UV4Kind
  21633. * - BABYLON.VertexBuffer.UV5Kind
  21634. * - BABYLON.VertexBuffer.UV6Kind
  21635. * - BABYLON.VertexBuffer.ColorKind
  21636. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21637. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21638. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21639. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21640. */
  21641. Mesh.prototype.getVertexBuffer = function (kind) {
  21642. if (!this._geometry) {
  21643. return undefined;
  21644. }
  21645. return this._geometry.getVertexBuffer(kind);
  21646. };
  21647. /**
  21648. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21649. * Possible `kind` values :
  21650. * - BABYLON.VertexBuffer.PositionKind
  21651. * - BABYLON.VertexBuffer.UVKind
  21652. * - BABYLON.VertexBuffer.UV2Kind
  21653. * - BABYLON.VertexBuffer.UV3Kind
  21654. * - BABYLON.VertexBuffer.UV4Kind
  21655. * - BABYLON.VertexBuffer.UV5Kind
  21656. * - BABYLON.VertexBuffer.UV6Kind
  21657. * - BABYLON.VertexBuffer.ColorKind
  21658. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21659. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21660. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21661. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21662. */
  21663. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21664. if (!this._geometry) {
  21665. if (this._delayInfo) {
  21666. return this._delayInfo.indexOf(kind) !== -1;
  21667. }
  21668. return false;
  21669. }
  21670. return this._geometry.isVerticesDataPresent(kind);
  21671. };
  21672. /**
  21673. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21674. * Possible `kind` values :
  21675. * - BABYLON.VertexBuffer.PositionKind
  21676. * - BABYLON.VertexBuffer.UVKind
  21677. * - BABYLON.VertexBuffer.UV2Kind
  21678. * - BABYLON.VertexBuffer.UV3Kind
  21679. * - BABYLON.VertexBuffer.UV4Kind
  21680. * - BABYLON.VertexBuffer.UV5Kind
  21681. * - BABYLON.VertexBuffer.UV6Kind
  21682. * - BABYLON.VertexBuffer.ColorKind
  21683. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21684. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21685. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21686. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21687. */
  21688. Mesh.prototype.getVerticesDataKinds = function () {
  21689. if (!this._geometry) {
  21690. var result = [];
  21691. if (this._delayInfo) {
  21692. this._delayInfo.forEach(function (kind, index, array) {
  21693. result.push(kind);
  21694. });
  21695. }
  21696. return result;
  21697. }
  21698. return this._geometry.getVerticesDataKinds();
  21699. };
  21700. /**
  21701. * Returns a positive integer : the total number of indices in this mesh geometry.
  21702. * Returns zero if the mesh has no geometry.
  21703. */
  21704. Mesh.prototype.getTotalIndices = function () {
  21705. if (!this._geometry) {
  21706. return 0;
  21707. }
  21708. return this._geometry.getTotalIndices();
  21709. };
  21710. /**
  21711. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21712. * 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.
  21713. * Returns an empty array if the mesh has no geometry.
  21714. */
  21715. Mesh.prototype.getIndices = function (copyWhenShared) {
  21716. if (!this._geometry) {
  21717. return [];
  21718. }
  21719. return this._geometry.getIndices(copyWhenShared);
  21720. };
  21721. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21722. get: function () {
  21723. return this._masterMesh !== null && this._masterMesh !== undefined;
  21724. },
  21725. enumerable: true,
  21726. configurable: true
  21727. });
  21728. /**
  21729. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21730. */
  21731. Mesh.prototype.isReady = function () {
  21732. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21733. return false;
  21734. }
  21735. return _super.prototype.isReady.call(this);
  21736. };
  21737. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21738. get: function () {
  21739. return this._sideOrientation;
  21740. },
  21741. /**
  21742. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21743. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21744. */
  21745. set: function (sideO) {
  21746. this._sideOrientation = sideO;
  21747. },
  21748. enumerable: true,
  21749. configurable: true
  21750. });
  21751. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21752. /**
  21753. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21754. * This property is pertinent only for updatable parametric shapes.
  21755. */
  21756. get: function () {
  21757. return this._areNormalsFrozen;
  21758. },
  21759. enumerable: true,
  21760. configurable: true
  21761. });
  21762. /**
  21763. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21764. * It has no effect at all on other shapes.
  21765. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21766. * Returns the Mesh.
  21767. */
  21768. Mesh.prototype.freezeNormals = function () {
  21769. this._areNormalsFrozen = true;
  21770. return this;
  21771. };
  21772. /**
  21773. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21774. * It has no effect at all on other shapes.
  21775. * It reactivates the mesh normals computation if it was previously frozen.
  21776. * Returns the Mesh.
  21777. */
  21778. Mesh.prototype.unfreezeNormals = function () {
  21779. this._areNormalsFrozen = false;
  21780. return this;
  21781. };
  21782. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21783. /**
  21784. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21785. */
  21786. set: function (count) {
  21787. this._overridenInstanceCount = count;
  21788. },
  21789. enumerable: true,
  21790. configurable: true
  21791. });
  21792. // Methods
  21793. Mesh.prototype._preActivate = function () {
  21794. var sceneRenderId = this.getScene().getRenderId();
  21795. if (this._preActivateId === sceneRenderId) {
  21796. return this;
  21797. }
  21798. this._preActivateId = sceneRenderId;
  21799. this._visibleInstances = null;
  21800. return this;
  21801. };
  21802. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21803. if (this._visibleInstances) {
  21804. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21805. }
  21806. return this;
  21807. };
  21808. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21809. if (!this._visibleInstances) {
  21810. this._visibleInstances = {};
  21811. this._visibleInstances.defaultRenderId = renderId;
  21812. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21813. }
  21814. if (!this._visibleInstances[renderId]) {
  21815. this._visibleInstances[renderId] = new Array();
  21816. }
  21817. this._visibleInstances[renderId].push(instance);
  21818. return this;
  21819. };
  21820. /**
  21821. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21822. * This means the mesh underlying bounding box and sphere are recomputed.
  21823. * Returns the Mesh.
  21824. */
  21825. Mesh.prototype.refreshBoundingInfo = function () {
  21826. if (this._boundingInfo.isLocked) {
  21827. return;
  21828. }
  21829. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21830. if (data) {
  21831. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21832. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21833. }
  21834. if (this.subMeshes) {
  21835. for (var index = 0; index < this.subMeshes.length; index++) {
  21836. this.subMeshes[index].refreshBoundingInfo();
  21837. }
  21838. }
  21839. this._updateBoundingInfo();
  21840. return this;
  21841. };
  21842. Mesh.prototype._createGlobalSubMesh = function (force) {
  21843. var totalVertices = this.getTotalVertices();
  21844. if (!totalVertices || !this.getIndices()) {
  21845. return null;
  21846. }
  21847. // Check if we need to recreate the submeshes
  21848. if (this.subMeshes && this.subMeshes.length > 0) {
  21849. var totalIndices = this.getIndices().length;
  21850. var needToRecreate = false;
  21851. if (force) {
  21852. needToRecreate = true;
  21853. }
  21854. else {
  21855. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21856. var submesh = _a[_i];
  21857. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21858. needToRecreate = true;
  21859. break;
  21860. }
  21861. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21862. needToRecreate = true;
  21863. break;
  21864. }
  21865. }
  21866. }
  21867. if (!needToRecreate) {
  21868. return;
  21869. }
  21870. }
  21871. this.releaseSubMeshes();
  21872. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21873. };
  21874. Mesh.prototype.subdivide = function (count) {
  21875. if (count < 1) {
  21876. return;
  21877. }
  21878. var totalIndices = this.getTotalIndices();
  21879. var subdivisionSize = (totalIndices / count) | 0;
  21880. var offset = 0;
  21881. // Ensure that subdivisionSize is a multiple of 3
  21882. while (subdivisionSize % 3 !== 0) {
  21883. subdivisionSize++;
  21884. }
  21885. this.releaseSubMeshes();
  21886. for (var index = 0; index < count; index++) {
  21887. if (offset >= totalIndices) {
  21888. break;
  21889. }
  21890. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21891. offset += subdivisionSize;
  21892. }
  21893. this.synchronizeInstances();
  21894. };
  21895. /**
  21896. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21897. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21898. * The `data` are either a numeric array either a Float32Array.
  21899. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21900. * 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).
  21901. * Note that a new underlying VertexBuffer object is created each call.
  21902. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21903. *
  21904. * Possible `kind` values :
  21905. * - BABYLON.VertexBuffer.PositionKind
  21906. * - BABYLON.VertexBuffer.UVKind
  21907. * - BABYLON.VertexBuffer.UV2Kind
  21908. * - BABYLON.VertexBuffer.UV3Kind
  21909. * - BABYLON.VertexBuffer.UV4Kind
  21910. * - BABYLON.VertexBuffer.UV5Kind
  21911. * - BABYLON.VertexBuffer.UV6Kind
  21912. * - BABYLON.VertexBuffer.ColorKind
  21913. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21914. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21915. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21916. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21917. *
  21918. * Returns the Mesh.
  21919. */
  21920. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21921. if (!this._geometry) {
  21922. var vertexData = new BABYLON.VertexData();
  21923. vertexData.set(data, kind);
  21924. var scene = this.getScene();
  21925. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21926. }
  21927. else {
  21928. this._geometry.setVerticesData(kind, data, updatable, stride);
  21929. }
  21930. return this;
  21931. };
  21932. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21933. if (updatable === void 0) { updatable = true; }
  21934. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21935. return;
  21936. }
  21937. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21938. };
  21939. /**
  21940. * Sets the mesh VertexBuffer.
  21941. * Returns the Mesh.
  21942. */
  21943. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21944. if (!this._geometry) {
  21945. var scene = this.getScene();
  21946. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21947. }
  21948. this._geometry.setVerticesBuffer(buffer);
  21949. return this;
  21950. };
  21951. /**
  21952. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21953. * If the mesh has no geometry, it is simply returned as it is.
  21954. * The `data` are either a numeric array either a Float32Array.
  21955. * No new underlying VertexBuffer object is created.
  21956. * 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.
  21957. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21958. *
  21959. * Possible `kind` values :
  21960. * - BABYLON.VertexBuffer.PositionKind
  21961. * - BABYLON.VertexBuffer.UVKind
  21962. * - BABYLON.VertexBuffer.UV2Kind
  21963. * - BABYLON.VertexBuffer.UV3Kind
  21964. * - BABYLON.VertexBuffer.UV4Kind
  21965. * - BABYLON.VertexBuffer.UV5Kind
  21966. * - BABYLON.VertexBuffer.UV6Kind
  21967. * - BABYLON.VertexBuffer.ColorKind
  21968. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21969. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21970. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21971. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21972. *
  21973. * Returns the Mesh.
  21974. */
  21975. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21976. if (!this._geometry) {
  21977. return;
  21978. }
  21979. if (!makeItUnique) {
  21980. this._geometry.updateVerticesData(kind, data, updateExtends);
  21981. }
  21982. else {
  21983. this.makeGeometryUnique();
  21984. this.updateVerticesData(kind, data, updateExtends, false);
  21985. }
  21986. return this;
  21987. };
  21988. /**
  21989. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21990. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21991. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21992. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21993. * Returns the Mesh.
  21994. */
  21995. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21996. if (computeNormals === void 0) { computeNormals = true; }
  21997. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21998. positionFunction(positions);
  21999. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22000. if (computeNormals) {
  22001. var indices = this.getIndices();
  22002. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22003. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22004. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22005. }
  22006. return this;
  22007. };
  22008. /**
  22009. * Creates a un-shared specific occurence of the geometry for the mesh.
  22010. * Returns the Mesh.
  22011. */
  22012. Mesh.prototype.makeGeometryUnique = function () {
  22013. if (!this._geometry) {
  22014. return;
  22015. }
  22016. var oldGeometry = this._geometry;
  22017. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22018. oldGeometry.releaseForMesh(this, true);
  22019. geometry.applyToMesh(this);
  22020. return this;
  22021. };
  22022. /**
  22023. * Sets the mesh indices.
  22024. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22025. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22026. * This method creates a new index buffer each call.
  22027. * Returns the Mesh.
  22028. */
  22029. Mesh.prototype.setIndices = function (indices, totalVertices) {
  22030. if (!this._geometry) {
  22031. var vertexData = new BABYLON.VertexData();
  22032. vertexData.indices = indices;
  22033. var scene = this.getScene();
  22034. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  22035. }
  22036. else {
  22037. this._geometry.setIndices(indices, totalVertices);
  22038. }
  22039. return this;
  22040. };
  22041. /**
  22042. * Invert the geometry to move from a right handed system to a left handed one.
  22043. * Returns the Mesh.
  22044. */
  22045. Mesh.prototype.toLeftHanded = function () {
  22046. if (!this._geometry) {
  22047. return;
  22048. }
  22049. this._geometry.toLeftHanded();
  22050. return this;
  22051. };
  22052. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22053. var engine = this.getScene().getEngine();
  22054. // Wireframe
  22055. var indexToBind;
  22056. if (this._unIndexed) {
  22057. indexToBind = null;
  22058. }
  22059. else {
  22060. switch (fillMode) {
  22061. case BABYLON.Material.PointFillMode:
  22062. indexToBind = null;
  22063. break;
  22064. case BABYLON.Material.WireFrameFillMode:
  22065. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22066. break;
  22067. default:
  22068. case BABYLON.Material.TriangleFillMode:
  22069. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22070. break;
  22071. }
  22072. }
  22073. // VBOs
  22074. this._geometry._bind(effect, indexToBind);
  22075. return this;
  22076. };
  22077. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  22078. if (alternate === void 0) { alternate = false; }
  22079. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22080. return this;
  22081. }
  22082. this.onBeforeDrawObservable.notifyObservers(this);
  22083. var scene = this.getScene();
  22084. var engine = scene.getEngine();
  22085. // Draw order
  22086. switch (fillMode) {
  22087. case BABYLON.Material.PointFillMode:
  22088. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22089. break;
  22090. case BABYLON.Material.WireFrameFillMode:
  22091. if (this._unIndexed) {
  22092. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22093. }
  22094. else {
  22095. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22096. }
  22097. break;
  22098. default:
  22099. if (this._unIndexed) {
  22100. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22101. }
  22102. else {
  22103. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22104. }
  22105. }
  22106. if (scene._isAlternateRenderingEnabled && !alternate) {
  22107. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  22108. scene._switchToAlternateCameraConfiguration(true);
  22109. this._effectiveMaterial.bindView(effect);
  22110. this._effectiveMaterial.bindViewProjection(effect);
  22111. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  22112. this._draw(subMesh, fillMode, instancesCount, true);
  22113. engine.setViewport(scene.activeCamera.viewport);
  22114. scene._switchToAlternateCameraConfiguration(false);
  22115. this._effectiveMaterial.bindView(effect);
  22116. this._effectiveMaterial.bindViewProjection(effect);
  22117. }
  22118. return this;
  22119. };
  22120. /**
  22121. * Registers for this mesh a javascript function called just before the rendering process.
  22122. * This function is passed the current mesh.
  22123. * Return the Mesh.
  22124. */
  22125. Mesh.prototype.registerBeforeRender = function (func) {
  22126. this.onBeforeRenderObservable.add(func);
  22127. return this;
  22128. };
  22129. /**
  22130. * Disposes a previously registered javascript function called before the rendering.
  22131. * This function is passed the current mesh.
  22132. * Returns the Mesh.
  22133. */
  22134. Mesh.prototype.unregisterBeforeRender = function (func) {
  22135. this.onBeforeRenderObservable.removeCallback(func);
  22136. return this;
  22137. };
  22138. /**
  22139. * Registers for this mesh a javascript function called just after the rendering is complete.
  22140. * This function is passed the current mesh.
  22141. * Returns the Mesh.
  22142. */
  22143. Mesh.prototype.registerAfterRender = function (func) {
  22144. this.onAfterRenderObservable.add(func);
  22145. return this;
  22146. };
  22147. /**
  22148. * Disposes a previously registered javascript function called after the rendering.
  22149. * This function is passed the current mesh.
  22150. * Return the Mesh.
  22151. */
  22152. Mesh.prototype.unregisterAfterRender = function (func) {
  22153. this.onAfterRenderObservable.removeCallback(func);
  22154. return this;
  22155. };
  22156. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22157. var scene = this.getScene();
  22158. this._batchCache.mustReturn = false;
  22159. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22160. this._batchCache.visibleInstances[subMeshId] = null;
  22161. if (this._visibleInstances) {
  22162. var currentRenderId = scene.getRenderId();
  22163. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22164. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22165. var selfRenderId = this._renderId;
  22166. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22167. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22168. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22169. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22170. }
  22171. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22172. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22173. this._batchCache.mustReturn = true;
  22174. return this._batchCache;
  22175. }
  22176. if (currentRenderId !== selfRenderId) {
  22177. this._batchCache.renderSelf[subMeshId] = false;
  22178. }
  22179. }
  22180. this._renderIdForInstances[subMeshId] = currentRenderId;
  22181. }
  22182. return this._batchCache;
  22183. };
  22184. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22185. var visibleInstances = batch.visibleInstances[subMesh._id];
  22186. var matricesCount = visibleInstances.length + 1;
  22187. var bufferSize = matricesCount * 16 * 4;
  22188. var currentInstancesBufferSize = this._instancesBufferSize;
  22189. var instancesBuffer = this._instancesBuffer;
  22190. while (this._instancesBufferSize < bufferSize) {
  22191. this._instancesBufferSize *= 2;
  22192. }
  22193. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22194. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22195. }
  22196. var offset = 0;
  22197. var instancesCount = 0;
  22198. var world = this.getWorldMatrix();
  22199. if (batch.renderSelf[subMesh._id]) {
  22200. world.copyToArray(this._instancesData, offset);
  22201. offset += 16;
  22202. instancesCount++;
  22203. }
  22204. if (visibleInstances) {
  22205. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22206. var instance = visibleInstances[instanceIndex];
  22207. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22208. offset += 16;
  22209. instancesCount++;
  22210. }
  22211. }
  22212. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22213. if (instancesBuffer) {
  22214. instancesBuffer.dispose();
  22215. }
  22216. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22217. this._instancesBuffer = instancesBuffer;
  22218. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22219. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22220. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22221. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22222. }
  22223. else {
  22224. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22225. }
  22226. this._bind(subMesh, effect, fillMode);
  22227. this._draw(subMesh, fillMode, instancesCount);
  22228. engine.unbindInstanceAttributes();
  22229. return this;
  22230. };
  22231. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22232. var scene = this.getScene();
  22233. var engine = scene.getEngine();
  22234. if (hardwareInstancedRendering) {
  22235. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22236. }
  22237. else {
  22238. if (batch.renderSelf[subMesh._id]) {
  22239. // Draw
  22240. if (onBeforeDraw) {
  22241. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22242. }
  22243. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22244. }
  22245. if (batch.visibleInstances[subMesh._id]) {
  22246. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22247. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22248. // World
  22249. var world = instance.getWorldMatrix();
  22250. if (onBeforeDraw) {
  22251. onBeforeDraw(true, world, effectiveMaterial);
  22252. }
  22253. // Draw
  22254. this._draw(subMesh, fillMode);
  22255. }
  22256. }
  22257. }
  22258. return this;
  22259. };
  22260. /**
  22261. * Triggers the draw call for the mesh.
  22262. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22263. * Returns the Mesh.
  22264. */
  22265. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22266. this.checkOcclusionQuery();
  22267. if (this._isOccluded) {
  22268. return;
  22269. }
  22270. var scene = this.getScene();
  22271. // Managing instances
  22272. var batch = this._getInstancesRenderList(subMesh._id);
  22273. if (batch.mustReturn) {
  22274. return this;
  22275. }
  22276. // Checking geometry state
  22277. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22278. return this;
  22279. }
  22280. var callbackIndex;
  22281. this.onBeforeRenderObservable.notifyObservers(this);
  22282. var engine = scene.getEngine();
  22283. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22284. // Material
  22285. this._effectiveMaterial = subMesh.getMaterial();
  22286. if (!this._effectiveMaterial) {
  22287. return this;
  22288. }
  22289. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22290. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22291. return this;
  22292. }
  22293. }
  22294. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22295. return this;
  22296. }
  22297. // Alpha mode
  22298. if (enableAlphaMode) {
  22299. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  22300. }
  22301. // Outline - step 1
  22302. var savedDepthWrite = engine.getDepthWrite();
  22303. if (this.renderOutline) {
  22304. engine.setDepthWrite(false);
  22305. scene.getOutlineRenderer().render(subMesh, batch);
  22306. engine.setDepthWrite(savedDepthWrite);
  22307. }
  22308. var effect;
  22309. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22310. effect = subMesh.effect;
  22311. }
  22312. else {
  22313. effect = this._effectiveMaterial.getEffect();
  22314. }
  22315. this._effectiveMaterial._preBind(effect);
  22316. // Bind
  22317. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  22318. if (!hardwareInstancedRendering) {
  22319. this._bind(subMesh, effect, fillMode);
  22320. }
  22321. var world = this.getWorldMatrix();
  22322. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22323. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22324. }
  22325. else {
  22326. this._effectiveMaterial.bind(world, this);
  22327. }
  22328. // Draw
  22329. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22330. // Unbind
  22331. this._effectiveMaterial.unbind();
  22332. // Outline - step 2
  22333. if (this.renderOutline && savedDepthWrite) {
  22334. engine.setDepthWrite(true);
  22335. engine.setColorWrite(false);
  22336. scene.getOutlineRenderer().render(subMesh, batch);
  22337. engine.setColorWrite(true);
  22338. }
  22339. // Overlay
  22340. if (this.renderOverlay) {
  22341. var currentMode = engine.getAlphaMode();
  22342. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22343. scene.getOutlineRenderer().render(subMesh, batch, true);
  22344. engine.setAlphaMode(currentMode);
  22345. }
  22346. this.onAfterRenderObservable.notifyObservers(this);
  22347. return this;
  22348. };
  22349. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22350. if (isInstance) {
  22351. effectiveMaterial.bindOnlyWorldMatrix(world);
  22352. }
  22353. return this;
  22354. };
  22355. /**
  22356. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22357. */
  22358. Mesh.prototype.getEmittedParticleSystems = function () {
  22359. var results = new Array();
  22360. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22361. var particleSystem = this.getScene().particleSystems[index];
  22362. if (particleSystem.emitter === this) {
  22363. results.push(particleSystem);
  22364. }
  22365. }
  22366. return results;
  22367. };
  22368. /**
  22369. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22370. */
  22371. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22372. var results = new Array();
  22373. var descendants = this.getDescendants();
  22374. descendants.push(this);
  22375. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22376. var particleSystem = this.getScene().particleSystems[index];
  22377. var emitter = particleSystem.emitter;
  22378. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22379. results.push(particleSystem);
  22380. }
  22381. }
  22382. return results;
  22383. };
  22384. Mesh.prototype._checkDelayState = function () {
  22385. var scene = this.getScene();
  22386. if (this._geometry) {
  22387. this._geometry.load(scene);
  22388. }
  22389. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22390. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22391. this._queueLoad(this, scene);
  22392. }
  22393. return this;
  22394. };
  22395. Mesh.prototype._queueLoad = function (mesh, scene) {
  22396. var _this = this;
  22397. scene._addPendingData(mesh);
  22398. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22399. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22400. if (data instanceof ArrayBuffer) {
  22401. _this._delayLoadingFunction(data, _this);
  22402. }
  22403. else {
  22404. _this._delayLoadingFunction(JSON.parse(data), _this);
  22405. }
  22406. _this.instances.forEach(function (instance) {
  22407. instance._syncSubMeshes();
  22408. });
  22409. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22410. scene._removePendingData(_this);
  22411. }, function () { }, scene.database, getBinaryData);
  22412. return this;
  22413. };
  22414. /**
  22415. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22416. */
  22417. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22418. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22419. return false;
  22420. }
  22421. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22422. return false;
  22423. }
  22424. this._checkDelayState();
  22425. return true;
  22426. };
  22427. /**
  22428. * Sets the mesh material by the material or multiMaterial `id` property.
  22429. * The material `id` is a string identifying the material or the multiMaterial.
  22430. * This method returns the Mesh.
  22431. */
  22432. Mesh.prototype.setMaterialByID = function (id) {
  22433. var materials = this.getScene().materials;
  22434. var index;
  22435. for (index = materials.length - 1; index > -1; index--) {
  22436. if (materials[index].id === id) {
  22437. this.material = materials[index];
  22438. return this;
  22439. }
  22440. }
  22441. // Multi
  22442. var multiMaterials = this.getScene().multiMaterials;
  22443. for (index = multiMaterials.length - 1; index > -1; index--) {
  22444. if (multiMaterials[index].id === id) {
  22445. this.material = multiMaterials[index];
  22446. return this;
  22447. }
  22448. }
  22449. return this;
  22450. };
  22451. /**
  22452. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22453. */
  22454. Mesh.prototype.getAnimatables = function () {
  22455. var results = [];
  22456. if (this.material) {
  22457. results.push(this.material);
  22458. }
  22459. if (this.skeleton) {
  22460. results.push(this.skeleton);
  22461. }
  22462. return results;
  22463. };
  22464. /**
  22465. * Modifies the mesh geometry according to the passed transformation matrix.
  22466. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22467. * The mesh normals are modified accordingly the same transformation.
  22468. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22469. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22470. * Returns the Mesh.
  22471. */
  22472. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22473. // Position
  22474. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22475. return this;
  22476. }
  22477. var submeshes = this.subMeshes.splice(0);
  22478. this._resetPointsArrayCache();
  22479. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22480. var temp = [];
  22481. var index;
  22482. for (index = 0; index < data.length; index += 3) {
  22483. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22484. }
  22485. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22486. // Normals
  22487. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22488. return this;
  22489. }
  22490. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22491. temp = [];
  22492. for (index = 0; index < data.length; index += 3) {
  22493. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22494. }
  22495. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22496. // flip faces?
  22497. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22498. this.flipFaces();
  22499. }
  22500. // Restore submeshes
  22501. this.releaseSubMeshes();
  22502. this.subMeshes = submeshes;
  22503. return this;
  22504. };
  22505. /**
  22506. * Modifies the mesh geometry according to its own current World Matrix.
  22507. * The mesh World Matrix is then reset.
  22508. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22509. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22510. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22511. * Returns the Mesh.
  22512. */
  22513. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22514. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22515. this.scaling.copyFromFloats(1, 1, 1);
  22516. this.position.copyFromFloats(0, 0, 0);
  22517. this.rotation.copyFromFloats(0, 0, 0);
  22518. //only if quaternion is already set
  22519. if (this.rotationQuaternion) {
  22520. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22521. }
  22522. this._worldMatrix = BABYLON.Matrix.Identity();
  22523. return this;
  22524. };
  22525. Object.defineProperty(Mesh.prototype, "_positions", {
  22526. // Cache
  22527. get: function () {
  22528. if (this._geometry) {
  22529. return this._geometry._positions;
  22530. }
  22531. return null;
  22532. },
  22533. enumerable: true,
  22534. configurable: true
  22535. });
  22536. Mesh.prototype._resetPointsArrayCache = function () {
  22537. if (this._geometry) {
  22538. this._geometry._resetPointsArrayCache();
  22539. }
  22540. return this;
  22541. };
  22542. Mesh.prototype._generatePointsArray = function () {
  22543. if (this._geometry) {
  22544. return this._geometry._generatePointsArray();
  22545. }
  22546. return false;
  22547. };
  22548. /**
  22549. * Returns a new Mesh object generated from the current mesh properties.
  22550. * This method must not get confused with createInstance().
  22551. * The parameter `name` is a string, the name given to the new mesh.
  22552. * The optional parameter `newParent` can be any Node object (default `null`).
  22553. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22554. * 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.
  22555. */
  22556. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22557. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22558. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22559. };
  22560. /**
  22561. * Disposes the mesh.
  22562. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22563. */
  22564. Mesh.prototype.dispose = function (doNotRecurse) {
  22565. var _this = this;
  22566. this.morphTargetManager = undefined;
  22567. if (this._geometry) {
  22568. this._geometry.releaseForMesh(this, true);
  22569. }
  22570. // Sources
  22571. var meshes = this.getScene().meshes;
  22572. meshes.forEach(function (mesh) {
  22573. if (mesh._source && mesh._source === _this) {
  22574. mesh._source = null;
  22575. }
  22576. });
  22577. this._source = null;
  22578. // Instances
  22579. if (this._instancesBuffer) {
  22580. this._instancesBuffer.dispose();
  22581. this._instancesBuffer = null;
  22582. }
  22583. while (this.instances.length) {
  22584. this.instances[0].dispose();
  22585. }
  22586. // Highlight layers.
  22587. var highlightLayers = this.getScene().highlightLayers;
  22588. for (var i = 0; i < highlightLayers.length; i++) {
  22589. var highlightLayer = highlightLayers[i];
  22590. if (highlightLayer) {
  22591. highlightLayer.removeMesh(this);
  22592. highlightLayer.removeExcludedMesh(this);
  22593. }
  22594. }
  22595. _super.prototype.dispose.call(this, doNotRecurse);
  22596. };
  22597. /**
  22598. * Modifies the mesh geometry according to a displacement map.
  22599. * 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.
  22600. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22601. * This method returns nothing.
  22602. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22603. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22604. * 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.
  22605. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22606. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22607. *
  22608. * Returns the Mesh.
  22609. */
  22610. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22611. var _this = this;
  22612. var scene = this.getScene();
  22613. var onload = function (img) {
  22614. // Getting height map data
  22615. var canvas = document.createElement("canvas");
  22616. var context = canvas.getContext("2d");
  22617. var heightMapWidth = img.width;
  22618. var heightMapHeight = img.height;
  22619. canvas.width = heightMapWidth;
  22620. canvas.height = heightMapHeight;
  22621. context.drawImage(img, 0, 0);
  22622. // Create VertexData from map data
  22623. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22624. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22625. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22626. //execute success callback, if set
  22627. if (onSuccess) {
  22628. onSuccess(_this);
  22629. }
  22630. };
  22631. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22632. return this;
  22633. };
  22634. /**
  22635. * Modifies the mesh geometry according to a displacementMap buffer.
  22636. * 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.
  22637. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22638. * This method returns nothing.
  22639. * 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.
  22640. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22641. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22642. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22643. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22644. *
  22645. * Returns the Mesh.
  22646. */
  22647. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22648. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22649. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22650. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22651. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22652. return this;
  22653. }
  22654. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22655. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22656. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22657. var position = BABYLON.Vector3.Zero();
  22658. var normal = BABYLON.Vector3.Zero();
  22659. var uv = BABYLON.Vector2.Zero();
  22660. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22661. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22662. for (var index = 0; index < positions.length; index += 3) {
  22663. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22664. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22665. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22666. // Compute height
  22667. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22668. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22669. var pos = (u + v * heightMapWidth) * 4;
  22670. var r = buffer[pos] / 255.0;
  22671. var g = buffer[pos + 1] / 255.0;
  22672. var b = buffer[pos + 2] / 255.0;
  22673. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22674. normal.normalize();
  22675. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22676. position = position.add(normal);
  22677. position.toArray(positions, index);
  22678. }
  22679. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22680. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22681. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22682. return this;
  22683. };
  22684. /**
  22685. * Modify the mesh to get a flat shading rendering.
  22686. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22687. * This method returns the Mesh.
  22688. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22689. */
  22690. Mesh.prototype.convertToFlatShadedMesh = function () {
  22691. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22692. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22693. var kinds = this.getVerticesDataKinds();
  22694. var vbs = [];
  22695. var data = [];
  22696. var newdata = [];
  22697. var updatableNormals = false;
  22698. var kindIndex;
  22699. var kind;
  22700. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22701. kind = kinds[kindIndex];
  22702. var vertexBuffer = this.getVertexBuffer(kind);
  22703. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22704. updatableNormals = vertexBuffer.isUpdatable();
  22705. kinds.splice(kindIndex, 1);
  22706. kindIndex--;
  22707. continue;
  22708. }
  22709. vbs[kind] = vertexBuffer;
  22710. data[kind] = vbs[kind].getData();
  22711. newdata[kind] = [];
  22712. }
  22713. // Save previous submeshes
  22714. var previousSubmeshes = this.subMeshes.slice(0);
  22715. var indices = this.getIndices();
  22716. var totalIndices = this.getTotalIndices();
  22717. // Generating unique vertices per face
  22718. var index;
  22719. for (index = 0; index < totalIndices; index++) {
  22720. var vertexIndex = indices[index];
  22721. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22722. kind = kinds[kindIndex];
  22723. var stride = vbs[kind].getStrideSize();
  22724. for (var offset = 0; offset < stride; offset++) {
  22725. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22726. }
  22727. }
  22728. }
  22729. // Updating faces & normal
  22730. var normals = [];
  22731. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22732. for (index = 0; index < totalIndices; index += 3) {
  22733. indices[index] = index;
  22734. indices[index + 1] = index + 1;
  22735. indices[index + 2] = index + 2;
  22736. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22737. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22738. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22739. var p1p2 = p1.subtract(p2);
  22740. var p3p2 = p3.subtract(p2);
  22741. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22742. // Store same normals for every vertex
  22743. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22744. normals.push(normal.x);
  22745. normals.push(normal.y);
  22746. normals.push(normal.z);
  22747. }
  22748. }
  22749. this.setIndices(indices);
  22750. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22751. // Updating vertex buffers
  22752. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22753. kind = kinds[kindIndex];
  22754. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22755. }
  22756. // Updating submeshes
  22757. this.releaseSubMeshes();
  22758. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22759. var previousOne = previousSubmeshes[submeshIndex];
  22760. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22761. }
  22762. this.synchronizeInstances();
  22763. return this;
  22764. };
  22765. /**
  22766. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22767. * In other words, more vertices, no more indices and a single bigger VBO.
  22768. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22769. * Returns the Mesh.
  22770. */
  22771. Mesh.prototype.convertToUnIndexedMesh = function () {
  22772. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22773. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22774. var kinds = this.getVerticesDataKinds();
  22775. var vbs = [];
  22776. var data = [];
  22777. var newdata = [];
  22778. var updatableNormals = false;
  22779. var kindIndex;
  22780. var kind;
  22781. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22782. kind = kinds[kindIndex];
  22783. var vertexBuffer = this.getVertexBuffer(kind);
  22784. vbs[kind] = vertexBuffer;
  22785. data[kind] = vbs[kind].getData();
  22786. newdata[kind] = [];
  22787. }
  22788. // Save previous submeshes
  22789. var previousSubmeshes = this.subMeshes.slice(0);
  22790. var indices = this.getIndices();
  22791. var totalIndices = this.getTotalIndices();
  22792. // Generating unique vertices per face
  22793. var index;
  22794. for (index = 0; index < totalIndices; index++) {
  22795. var vertexIndex = indices[index];
  22796. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22797. kind = kinds[kindIndex];
  22798. var stride = vbs[kind].getStrideSize();
  22799. for (var offset = 0; offset < stride; offset++) {
  22800. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22801. }
  22802. }
  22803. }
  22804. // Updating indices
  22805. for (index = 0; index < totalIndices; index += 3) {
  22806. indices[index] = index;
  22807. indices[index + 1] = index + 1;
  22808. indices[index + 2] = index + 2;
  22809. }
  22810. this.setIndices(indices);
  22811. // Updating vertex buffers
  22812. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22813. kind = kinds[kindIndex];
  22814. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22815. }
  22816. // Updating submeshes
  22817. this.releaseSubMeshes();
  22818. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22819. var previousOne = previousSubmeshes[submeshIndex];
  22820. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22821. }
  22822. this._unIndexed = true;
  22823. this.synchronizeInstances();
  22824. return this;
  22825. };
  22826. /**
  22827. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22828. * This method returns the Mesh.
  22829. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22830. */
  22831. Mesh.prototype.flipFaces = function (flipNormals) {
  22832. if (flipNormals === void 0) { flipNormals = false; }
  22833. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22834. var i;
  22835. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22836. for (i = 0; i < vertex_data.normals.length; i++) {
  22837. vertex_data.normals[i] *= -1;
  22838. }
  22839. }
  22840. var temp;
  22841. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22842. // reassign indices
  22843. temp = vertex_data.indices[i + 1];
  22844. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22845. vertex_data.indices[i + 2] = temp;
  22846. }
  22847. vertex_data.applyToMesh(this);
  22848. return this;
  22849. };
  22850. // Instances
  22851. /**
  22852. * Creates a new InstancedMesh object from the mesh model.
  22853. * An instance shares the same properties and the same material than its model.
  22854. * Only these properties of each instance can then be set individually :
  22855. * - position
  22856. * - rotation
  22857. * - rotationQuaternion
  22858. * - setPivotMatrix
  22859. * - scaling
  22860. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22861. * Warning : this method is not supported for Line mesh and LineSystem
  22862. */
  22863. Mesh.prototype.createInstance = function (name) {
  22864. return new BABYLON.InstancedMesh(name, this);
  22865. };
  22866. /**
  22867. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22868. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22869. * This method returns the Mesh.
  22870. */
  22871. Mesh.prototype.synchronizeInstances = function () {
  22872. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22873. var instance = this.instances[instanceIndex];
  22874. instance._syncSubMeshes();
  22875. }
  22876. return this;
  22877. };
  22878. /**
  22879. * Simplify the mesh according to the given array of settings.
  22880. * Function will return immediately and will simplify async. It returns the Mesh.
  22881. * @param settings a collection of simplification settings.
  22882. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22883. * @param type the type of simplification to run.
  22884. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22885. */
  22886. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22887. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22888. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22889. this.getScene().simplificationQueue.addTask({
  22890. settings: settings,
  22891. parallelProcessing: parallelProcessing,
  22892. mesh: this,
  22893. simplificationType: simplificationType,
  22894. successCallback: successCallback
  22895. });
  22896. return this;
  22897. };
  22898. /**
  22899. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22900. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22901. * This should be used together with the simplification to avoid disappearing triangles.
  22902. * Returns the Mesh.
  22903. * @param successCallback an optional success callback to be called after the optimization finished.
  22904. */
  22905. Mesh.prototype.optimizeIndices = function (successCallback) {
  22906. var _this = this;
  22907. var indices = this.getIndices();
  22908. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22909. var vectorPositions = [];
  22910. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22911. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22912. }
  22913. var dupes = [];
  22914. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22915. var realPos = vectorPositions.length - 1 - iteration;
  22916. var testedPosition = vectorPositions[realPos];
  22917. for (var j = 0; j < realPos; ++j) {
  22918. var againstPosition = vectorPositions[j];
  22919. if (testedPosition.equals(againstPosition)) {
  22920. dupes[realPos] = j;
  22921. break;
  22922. }
  22923. }
  22924. }, function () {
  22925. for (var i = 0; i < indices.length; ++i) {
  22926. indices[i] = dupes[indices[i]] || indices[i];
  22927. }
  22928. //indices are now reordered
  22929. var originalSubMeshes = _this.subMeshes.slice(0);
  22930. _this.setIndices(indices);
  22931. _this.subMeshes = originalSubMeshes;
  22932. if (successCallback) {
  22933. successCallback(_this);
  22934. }
  22935. });
  22936. return this;
  22937. };
  22938. Mesh.prototype.serialize = function (serializationObject) {
  22939. serializationObject.name = this.name;
  22940. serializationObject.id = this.id;
  22941. serializationObject.type = this.getClassName();
  22942. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22943. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22944. }
  22945. serializationObject.position = this.position.asArray();
  22946. if (this.rotationQuaternion) {
  22947. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22948. }
  22949. else if (this.rotation) {
  22950. serializationObject.rotation = this.rotation.asArray();
  22951. }
  22952. serializationObject.scaling = this.scaling.asArray();
  22953. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22954. serializationObject.isEnabled = this.isEnabled();
  22955. serializationObject.isVisible = this.isVisible;
  22956. serializationObject.infiniteDistance = this.infiniteDistance;
  22957. serializationObject.pickable = this.isPickable;
  22958. serializationObject.receiveShadows = this.receiveShadows;
  22959. serializationObject.billboardMode = this.billboardMode;
  22960. serializationObject.visibility = this.visibility;
  22961. serializationObject.checkCollisions = this.checkCollisions;
  22962. serializationObject.isBlocker = this.isBlocker;
  22963. // Parent
  22964. if (this.parent) {
  22965. serializationObject.parentId = this.parent.id;
  22966. }
  22967. // Geometry
  22968. var geometry = this._geometry;
  22969. if (geometry) {
  22970. var geometryId = geometry.id;
  22971. serializationObject.geometryId = geometryId;
  22972. // SubMeshes
  22973. serializationObject.subMeshes = [];
  22974. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22975. var subMesh = this.subMeshes[subIndex];
  22976. serializationObject.subMeshes.push({
  22977. materialIndex: subMesh.materialIndex,
  22978. verticesStart: subMesh.verticesStart,
  22979. verticesCount: subMesh.verticesCount,
  22980. indexStart: subMesh.indexStart,
  22981. indexCount: subMesh.indexCount
  22982. });
  22983. }
  22984. }
  22985. // Material
  22986. if (this.material) {
  22987. serializationObject.materialId = this.material.id;
  22988. }
  22989. else {
  22990. this.material = null;
  22991. }
  22992. // Morph targets
  22993. if (this.morphTargetManager) {
  22994. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22995. }
  22996. // Skeleton
  22997. if (this.skeleton) {
  22998. serializationObject.skeletonId = this.skeleton.id;
  22999. }
  23000. // Physics
  23001. //TODO implement correct serialization for physics impostors.
  23002. if (this.getPhysicsImpostor()) {
  23003. var impostor = this.getPhysicsImpostor();
  23004. serializationObject.physicsMass = impostor.getParam("mass");
  23005. serializationObject.physicsFriction = impostor.getParam("friction");
  23006. serializationObject.physicsRestitution = impostor.getParam("mass");
  23007. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  23008. }
  23009. // Metadata
  23010. if (this.metadata) {
  23011. serializationObject.metadata = this.metadata;
  23012. }
  23013. // Instances
  23014. serializationObject.instances = [];
  23015. for (var index = 0; index < this.instances.length; index++) {
  23016. var instance = this.instances[index];
  23017. var serializationInstance = {
  23018. name: instance.name,
  23019. position: instance.position.asArray(),
  23020. scaling: instance.scaling.asArray()
  23021. };
  23022. if (instance.rotationQuaternion) {
  23023. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  23024. }
  23025. else if (instance.rotation) {
  23026. serializationInstance.rotation = instance.rotation.asArray();
  23027. }
  23028. serializationObject.instances.push(serializationInstance);
  23029. // Animations
  23030. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  23031. serializationInstance.ranges = instance.serializeAnimationRanges();
  23032. }
  23033. //
  23034. // Animations
  23035. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23036. serializationObject.ranges = this.serializeAnimationRanges();
  23037. // Layer mask
  23038. serializationObject.layerMask = this.layerMask;
  23039. // Alpha
  23040. serializationObject.alphaIndex = this.alphaIndex;
  23041. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  23042. // Overlay
  23043. serializationObject.overlayAlpha = this.overlayAlpha;
  23044. serializationObject.overlayColor = this.overlayColor.asArray();
  23045. serializationObject.renderOverlay = this.renderOverlay;
  23046. // Fog
  23047. serializationObject.applyFog = this.applyFog;
  23048. // Action Manager
  23049. if (this.actionManager) {
  23050. serializationObject.actions = this.actionManager.serialize(this.name);
  23051. }
  23052. };
  23053. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  23054. if (!this.geometry) {
  23055. return;
  23056. }
  23057. this._markSubMeshesAsAttributesDirty();
  23058. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  23059. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  23060. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  23061. this.morphTargetManager = undefined;
  23062. return;
  23063. }
  23064. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  23065. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  23066. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  23067. if (morphTarget.hasNormals) {
  23068. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  23069. }
  23070. if (morphTarget.hasTangents) {
  23071. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  23072. }
  23073. }
  23074. }
  23075. else {
  23076. var index = 0;
  23077. // Positions
  23078. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  23079. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  23080. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  23081. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  23082. }
  23083. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  23084. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  23085. }
  23086. index++;
  23087. }
  23088. }
  23089. };
  23090. // Statics
  23091. /**
  23092. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23093. * The parameter `parsedMesh` is the mesh to be copied.
  23094. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23095. */
  23096. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23097. var mesh;
  23098. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  23099. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  23100. }
  23101. else {
  23102. mesh = new Mesh(parsedMesh.name, scene);
  23103. }
  23104. mesh.id = parsedMesh.id;
  23105. if (BABYLON.Tags) {
  23106. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23107. }
  23108. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23109. if (parsedMesh.metadata !== undefined) {
  23110. mesh.metadata = parsedMesh.metadata;
  23111. }
  23112. if (parsedMesh.rotationQuaternion) {
  23113. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23114. }
  23115. else if (parsedMesh.rotation) {
  23116. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23117. }
  23118. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23119. if (parsedMesh.localMatrix) {
  23120. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23121. }
  23122. else if (parsedMesh.pivotMatrix) {
  23123. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23124. }
  23125. mesh.setEnabled(parsedMesh.isEnabled);
  23126. mesh.isVisible = parsedMesh.isVisible;
  23127. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23128. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23129. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23130. if (parsedMesh.applyFog !== undefined) {
  23131. mesh.applyFog = parsedMesh.applyFog;
  23132. }
  23133. if (parsedMesh.pickable !== undefined) {
  23134. mesh.isPickable = parsedMesh.pickable;
  23135. }
  23136. if (parsedMesh.alphaIndex !== undefined) {
  23137. mesh.alphaIndex = parsedMesh.alphaIndex;
  23138. }
  23139. mesh.receiveShadows = parsedMesh.receiveShadows;
  23140. mesh.billboardMode = parsedMesh.billboardMode;
  23141. if (parsedMesh.visibility !== undefined) {
  23142. mesh.visibility = parsedMesh.visibility;
  23143. }
  23144. mesh.checkCollisions = parsedMesh.checkCollisions;
  23145. if (parsedMesh.isBlocker !== undefined) {
  23146. mesh.isBlocker = parsedMesh.isBlocker;
  23147. }
  23148. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23149. // freezeWorldMatrix
  23150. if (parsedMesh.freezeWorldMatrix) {
  23151. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23152. }
  23153. // Parent
  23154. if (parsedMesh.parentId) {
  23155. mesh._waitingParentId = parsedMesh.parentId;
  23156. }
  23157. // Actions
  23158. if (parsedMesh.actions !== undefined) {
  23159. mesh._waitingActions = parsedMesh.actions;
  23160. }
  23161. // Overlay
  23162. if (parsedMesh.overlayAlpha !== undefined) {
  23163. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23164. }
  23165. if (parsedMesh.overlayColor !== undefined) {
  23166. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23167. }
  23168. if (parsedMesh.renderOverlay !== undefined) {
  23169. mesh.renderOverlay = parsedMesh.renderOverlay;
  23170. }
  23171. // Geometry
  23172. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23173. if (parsedMesh.delayLoadingFile) {
  23174. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23175. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23176. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23177. if (parsedMesh._binaryInfo) {
  23178. mesh._binaryInfo = parsedMesh._binaryInfo;
  23179. }
  23180. mesh._delayInfo = [];
  23181. if (parsedMesh.hasUVs) {
  23182. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23183. }
  23184. if (parsedMesh.hasUVs2) {
  23185. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23186. }
  23187. if (parsedMesh.hasUVs3) {
  23188. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23189. }
  23190. if (parsedMesh.hasUVs4) {
  23191. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23192. }
  23193. if (parsedMesh.hasUVs5) {
  23194. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23195. }
  23196. if (parsedMesh.hasUVs6) {
  23197. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23198. }
  23199. if (parsedMesh.hasColors) {
  23200. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23201. }
  23202. if (parsedMesh.hasMatricesIndices) {
  23203. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23204. }
  23205. if (parsedMesh.hasMatricesWeights) {
  23206. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23207. }
  23208. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23209. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23210. mesh._checkDelayState();
  23211. }
  23212. }
  23213. else {
  23214. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23215. }
  23216. // Material
  23217. if (parsedMesh.materialId) {
  23218. mesh.setMaterialByID(parsedMesh.materialId);
  23219. }
  23220. else {
  23221. mesh.material = null;
  23222. }
  23223. // Morph targets
  23224. if (parsedMesh.morphTargetManagerId > -1) {
  23225. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23226. }
  23227. // Skeleton
  23228. if (parsedMesh.skeletonId > -1) {
  23229. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23230. if (parsedMesh.numBoneInfluencers) {
  23231. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23232. }
  23233. }
  23234. // Animations
  23235. if (parsedMesh.animations) {
  23236. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23237. var parsedAnimation = parsedMesh.animations[animationIndex];
  23238. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23239. }
  23240. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23241. }
  23242. if (parsedMesh.autoAnimate) {
  23243. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23244. }
  23245. // Layer Mask
  23246. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23247. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23248. }
  23249. else {
  23250. mesh.layerMask = 0x0FFFFFFF;
  23251. }
  23252. // Physics
  23253. if (parsedMesh.physicsImpostor) {
  23254. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23255. mass: parsedMesh.physicsMass,
  23256. friction: parsedMesh.physicsFriction,
  23257. restitution: parsedMesh.physicsRestitution
  23258. }, scene);
  23259. }
  23260. // Instances
  23261. if (parsedMesh.instances) {
  23262. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23263. var parsedInstance = parsedMesh.instances[index];
  23264. var instance = mesh.createInstance(parsedInstance.name);
  23265. if (BABYLON.Tags) {
  23266. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23267. }
  23268. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23269. if (parsedInstance.parentId) {
  23270. instance._waitingParentId = parsedInstance.parentId;
  23271. }
  23272. if (parsedInstance.rotationQuaternion) {
  23273. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23274. }
  23275. else if (parsedInstance.rotation) {
  23276. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23277. }
  23278. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23279. instance.checkCollisions = mesh.checkCollisions;
  23280. if (parsedMesh.animations) {
  23281. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23282. parsedAnimation = parsedMesh.animations[animationIndex];
  23283. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23284. }
  23285. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23286. }
  23287. }
  23288. }
  23289. return mesh;
  23290. };
  23291. /**
  23292. * Creates a ribbon mesh.
  23293. * Please consider using the same method from the MeshBuilder class instead.
  23294. * 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.
  23295. *
  23296. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23297. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23298. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23299. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23300. * 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.
  23301. * 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.
  23302. * 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
  23303. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23304. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23305. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23306. */
  23307. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23308. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23309. pathArray: pathArray,
  23310. closeArray: closeArray,
  23311. closePath: closePath,
  23312. offset: offset,
  23313. updatable: updatable,
  23314. sideOrientation: sideOrientation,
  23315. instance: instance
  23316. }, scene);
  23317. };
  23318. /**
  23319. * Creates a plane polygonal mesh. By default, this is a disc.
  23320. * Please consider using the same method from the MeshBuilder class instead.
  23321. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23322. * 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.
  23323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23324. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23326. */
  23327. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23328. var options = {
  23329. radius: radius,
  23330. tessellation: tessellation,
  23331. sideOrientation: sideOrientation,
  23332. updatable: updatable
  23333. };
  23334. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23335. };
  23336. /**
  23337. * Creates a box mesh.
  23338. * Please consider using the same method from the MeshBuilder class instead.
  23339. * The parameter `size` sets the size (float) of each box side (default 1).
  23340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23341. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23343. */
  23344. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23345. var options = {
  23346. size: size,
  23347. sideOrientation: sideOrientation,
  23348. updatable: updatable
  23349. };
  23350. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23351. };
  23352. /**
  23353. * Creates a sphere mesh.
  23354. * Please consider using the same method from the MeshBuilder class instead.
  23355. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23356. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23357. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23358. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23360. */
  23361. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23362. var options = {
  23363. segments: segments,
  23364. diameterX: diameter,
  23365. diameterY: diameter,
  23366. diameterZ: diameter,
  23367. sideOrientation: sideOrientation,
  23368. updatable: updatable
  23369. };
  23370. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23371. };
  23372. /**
  23373. * Creates a cylinder or a cone mesh.
  23374. * Please consider using the same method from the MeshBuilder class instead.
  23375. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23376. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23377. * 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.
  23378. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23379. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23380. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23381. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23382. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23383. */
  23384. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23385. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23386. if (scene !== undefined) {
  23387. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23388. updatable = scene;
  23389. }
  23390. scene = subdivisions;
  23391. subdivisions = 1;
  23392. }
  23393. var options = {
  23394. height: height,
  23395. diameterTop: diameterTop,
  23396. diameterBottom: diameterBottom,
  23397. tessellation: tessellation,
  23398. subdivisions: subdivisions,
  23399. sideOrientation: sideOrientation,
  23400. updatable: updatable
  23401. };
  23402. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23403. };
  23404. // Torus (Code from SharpDX.org)
  23405. /**
  23406. * Creates a torus mesh.
  23407. * Please consider using the same method from the MeshBuilder class instead.
  23408. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23409. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23410. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23411. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23412. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23413. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23414. */
  23415. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23416. var options = {
  23417. diameter: diameter,
  23418. thickness: thickness,
  23419. tessellation: tessellation,
  23420. sideOrientation: sideOrientation,
  23421. updatable: updatable
  23422. };
  23423. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23424. };
  23425. /**
  23426. * Creates a torus knot mesh.
  23427. * Please consider using the same method from the MeshBuilder class instead.
  23428. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23429. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23430. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23431. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23432. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23433. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23435. */
  23436. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23437. var options = {
  23438. radius: radius,
  23439. tube: tube,
  23440. radialSegments: radialSegments,
  23441. tubularSegments: tubularSegments,
  23442. p: p,
  23443. q: q,
  23444. sideOrientation: sideOrientation,
  23445. updatable: updatable
  23446. };
  23447. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23448. };
  23449. /**
  23450. * Creates a line mesh.
  23451. * Please consider using the same method from the MeshBuilder class instead.
  23452. * 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.
  23453. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23454. * The parameter `points` is an array successive Vector3.
  23455. * 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
  23456. * When updating an instance, remember that only point positions can change, not the number of points.
  23457. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23458. */
  23459. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23460. var options = {
  23461. points: points,
  23462. updatable: updatable,
  23463. instance: instance
  23464. };
  23465. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23466. };
  23467. /**
  23468. * Creates a dashed line mesh.
  23469. * Please consider using the same method from the MeshBuilder class instead.
  23470. * 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.
  23471. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23472. * The parameter `points` is an array successive Vector3.
  23473. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23474. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23475. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23476. * 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
  23477. * When updating an instance, remember that only point positions can change, not the number of points.
  23478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23479. */
  23480. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23481. var options = {
  23482. points: points,
  23483. dashSize: dashSize,
  23484. gapSize: gapSize,
  23485. dashNb: dashNb,
  23486. updatable: updatable,
  23487. instance: instance
  23488. };
  23489. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23490. };
  23491. /**
  23492. * Creates a polygon mesh.
  23493. * Please consider using the same method from the MeshBuilder class instead.
  23494. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23495. * 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.
  23496. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23497. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23498. * Remember you can only change the shape positions, not their number when updating a polygon.
  23499. */
  23500. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23501. var options = {
  23502. shape: shape,
  23503. holes: holes,
  23504. updatable: updatable,
  23505. sideOrientation: sideOrientation
  23506. };
  23507. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23508. };
  23509. /**
  23510. * Creates an extruded polygon mesh, with depth in the Y direction.
  23511. * Please consider using the same method from the MeshBuilder class instead.
  23512. */
  23513. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23514. var options = {
  23515. shape: shape,
  23516. holes: holes,
  23517. depth: depth,
  23518. updatable: updatable,
  23519. sideOrientation: sideOrientation
  23520. };
  23521. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23522. };
  23523. /**
  23524. * Creates an extruded shape mesh.
  23525. * 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.
  23526. * Please consider using the same method from the MeshBuilder class instead.
  23527. *
  23528. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23529. * 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
  23530. * extruded along the Z axis.
  23531. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23532. * 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.
  23533. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23534. * 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
  23535. * 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
  23536. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23537. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23538. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23540. */
  23541. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23542. var options = {
  23543. shape: shape,
  23544. path: path,
  23545. scale: scale,
  23546. rotation: rotation,
  23547. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23548. sideOrientation: sideOrientation,
  23549. instance: instance,
  23550. updatable: updatable
  23551. };
  23552. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23553. };
  23554. /**
  23555. * Creates an custom extruded shape mesh.
  23556. * 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.
  23557. * Please consider using the same method from the MeshBuilder class instead.
  23558. *
  23559. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23560. * 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
  23561. * extruded along the Z axis.
  23562. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23563. * 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
  23564. * and the distance of this point from the begining of the path :
  23565. * ```javascript
  23566. * var rotationFunction = function(i, distance) {
  23567. * // do things
  23568. * return rotationValue; }
  23569. * ```
  23570. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23571. * 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
  23572. * and the distance of this point from the begining of the path :
  23573. * ```javascript
  23574. * var scaleFunction = function(i, distance) {
  23575. * // do things
  23576. * return scaleValue;}
  23577. * ```
  23578. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23579. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23580. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23581. * 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
  23582. * 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
  23583. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23584. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23585. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23586. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23587. */
  23588. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23589. var options = {
  23590. shape: shape,
  23591. path: path,
  23592. scaleFunction: scaleFunction,
  23593. rotationFunction: rotationFunction,
  23594. ribbonCloseArray: ribbonCloseArray,
  23595. ribbonClosePath: ribbonClosePath,
  23596. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23597. sideOrientation: sideOrientation,
  23598. instance: instance,
  23599. updatable: updatable
  23600. };
  23601. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23602. };
  23603. /**
  23604. * Creates lathe mesh.
  23605. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23606. * Please consider using the same method from the MeshBuilder class instead.
  23607. * 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
  23608. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23609. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23610. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23611. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23614. */
  23615. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23616. var options = {
  23617. shape: shape,
  23618. radius: radius,
  23619. tessellation: tessellation,
  23620. sideOrientation: sideOrientation,
  23621. updatable: updatable
  23622. };
  23623. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23624. };
  23625. /**
  23626. * Creates a plane mesh.
  23627. * Please consider using the same method from the MeshBuilder class instead.
  23628. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23629. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23630. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23631. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23632. */
  23633. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23634. var options = {
  23635. size: size,
  23636. width: size,
  23637. height: size,
  23638. sideOrientation: sideOrientation,
  23639. updatable: updatable
  23640. };
  23641. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23642. };
  23643. /**
  23644. * Creates a ground mesh.
  23645. * Please consider using the same method from the MeshBuilder class instead.
  23646. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23647. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23649. */
  23650. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23651. var options = {
  23652. width: width,
  23653. height: height,
  23654. subdivisions: subdivisions,
  23655. updatable: updatable
  23656. };
  23657. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23658. };
  23659. /**
  23660. * Creates a tiled ground mesh.
  23661. * Please consider using the same method from the MeshBuilder class instead.
  23662. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23663. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23664. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23665. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23666. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23667. * numbers of subdivisions on the ground width and height of each tile.
  23668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23669. */
  23670. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23671. var options = {
  23672. xmin: xmin,
  23673. zmin: zmin,
  23674. xmax: xmax,
  23675. zmax: zmax,
  23676. subdivisions: subdivisions,
  23677. precision: precision,
  23678. updatable: updatable
  23679. };
  23680. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23681. };
  23682. /**
  23683. * Creates a ground mesh from a height map.
  23684. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23685. * Please consider using the same method from the MeshBuilder class instead.
  23686. * The parameter `url` sets the URL of the height map image resource.
  23687. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23688. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23689. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23690. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23691. * 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).
  23692. * This function is passed the newly built mesh :
  23693. * ```javascript
  23694. * function(mesh) { // do things
  23695. * return; }
  23696. * ```
  23697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23698. */
  23699. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23700. var options = {
  23701. width: width,
  23702. height: height,
  23703. subdivisions: subdivisions,
  23704. minHeight: minHeight,
  23705. maxHeight: maxHeight,
  23706. updatable: updatable,
  23707. onReady: onReady
  23708. };
  23709. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23710. };
  23711. /**
  23712. * Creates a tube mesh.
  23713. * 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.
  23714. * Please consider using the same method from the MeshBuilder class instead.
  23715. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23716. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23717. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23718. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23719. * 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.
  23720. * It must return a radius value (positive float) :
  23721. * ```javascript
  23722. * var radiusFunction = function(i, distance) {
  23723. * // do things
  23724. * return radius; }
  23725. * ```
  23726. * 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
  23727. * 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
  23728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23729. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23731. */
  23732. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23733. var options = {
  23734. path: path,
  23735. radius: radius,
  23736. tessellation: tessellation,
  23737. radiusFunction: radiusFunction,
  23738. arc: 1,
  23739. cap: cap,
  23740. updatable: updatable,
  23741. sideOrientation: sideOrientation,
  23742. instance: instance
  23743. };
  23744. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23745. };
  23746. /**
  23747. * Creates a polyhedron mesh.
  23748. * Please consider using the same method from the MeshBuilder class instead.
  23749. * 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
  23750. * to choose the wanted type.
  23751. * The parameter `size` (positive float, default 1) sets the polygon size.
  23752. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23753. * 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`.
  23754. * 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
  23755. * 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)`).
  23756. * 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
  23757. * 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.
  23758. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23759. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23761. */
  23762. Mesh.CreatePolyhedron = function (name, options, scene) {
  23763. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23764. };
  23765. /**
  23766. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23767. * Please consider using the same method from the MeshBuilder class instead.
  23768. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23769. * 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`).
  23770. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23771. * 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.
  23772. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23773. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23775. */
  23776. Mesh.CreateIcoSphere = function (name, options, scene) {
  23777. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23778. };
  23779. /**
  23780. * Creates a decal mesh.
  23781. * Please consider using the same method from the MeshBuilder class instead.
  23782. * 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.
  23783. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23784. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23785. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23786. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23787. */
  23788. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23789. var options = {
  23790. position: position,
  23791. normal: normal,
  23792. size: size,
  23793. angle: angle
  23794. };
  23795. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23796. };
  23797. // Skeletons
  23798. /**
  23799. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23800. */
  23801. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23802. var source;
  23803. if (!this._sourcePositions) {
  23804. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23805. this._sourcePositions = new Float32Array(source);
  23806. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23807. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23808. }
  23809. }
  23810. return this._sourcePositions;
  23811. };
  23812. /**
  23813. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23814. */
  23815. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23816. var source;
  23817. if (!this._sourceNormals) {
  23818. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23819. this._sourceNormals = new Float32Array(source);
  23820. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23821. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23822. }
  23823. }
  23824. return this._sourceNormals;
  23825. };
  23826. /**
  23827. * Updates the vertex buffer by applying transformation from the bones.
  23828. * Returns the Mesh.
  23829. *
  23830. * @param {skeleton} skeleton to apply
  23831. */
  23832. Mesh.prototype.applySkeleton = function (skeleton) {
  23833. if (!this.geometry) {
  23834. return this;
  23835. }
  23836. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23837. return this;
  23838. }
  23839. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23840. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23841. return this;
  23842. }
  23843. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23844. return this;
  23845. }
  23846. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23847. return this;
  23848. }
  23849. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23850. return this;
  23851. }
  23852. if (!this._sourcePositions) {
  23853. var submeshes = this.subMeshes.slice();
  23854. this.setPositionsForCPUSkinning();
  23855. this.subMeshes = submeshes;
  23856. }
  23857. if (!this._sourceNormals) {
  23858. this.setNormalsForCPUSkinning();
  23859. }
  23860. // positionsData checks for not being Float32Array will only pass at most once
  23861. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23862. if (!(positionsData instanceof Float32Array)) {
  23863. positionsData = new Float32Array(positionsData);
  23864. }
  23865. // normalsData checks for not being Float32Array will only pass at most once
  23866. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23867. if (!(normalsData instanceof Float32Array)) {
  23868. normalsData = new Float32Array(normalsData);
  23869. }
  23870. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23871. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23872. var needExtras = this.numBoneInfluencers > 4;
  23873. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23874. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23875. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23876. var tempVector3 = BABYLON.Vector3.Zero();
  23877. var finalMatrix = new BABYLON.Matrix();
  23878. var tempMatrix = new BABYLON.Matrix();
  23879. var matWeightIdx = 0;
  23880. var inf;
  23881. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23882. var weight;
  23883. for (inf = 0; inf < 4; inf++) {
  23884. weight = matricesWeightsData[matWeightIdx + inf];
  23885. if (weight > 0) {
  23886. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23887. finalMatrix.addToSelf(tempMatrix);
  23888. }
  23889. else
  23890. break;
  23891. }
  23892. if (needExtras) {
  23893. for (inf = 0; inf < 4; inf++) {
  23894. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23895. if (weight > 0) {
  23896. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23897. finalMatrix.addToSelf(tempMatrix);
  23898. }
  23899. else
  23900. break;
  23901. }
  23902. }
  23903. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23904. tempVector3.toArray(positionsData, index);
  23905. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23906. tempVector3.toArray(normalsData, index);
  23907. finalMatrix.reset();
  23908. }
  23909. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23910. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23911. return this;
  23912. };
  23913. // Tools
  23914. /**
  23915. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23916. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23917. */
  23918. Mesh.MinMax = function (meshes) {
  23919. var minVector = null;
  23920. var maxVector = null;
  23921. meshes.forEach(function (mesh, index, array) {
  23922. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23923. if (!minVector) {
  23924. minVector = boundingBox.minimumWorld;
  23925. maxVector = boundingBox.maximumWorld;
  23926. }
  23927. else {
  23928. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23929. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23930. }
  23931. });
  23932. return {
  23933. min: minVector,
  23934. max: maxVector
  23935. };
  23936. };
  23937. /**
  23938. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23939. */
  23940. Mesh.Center = function (meshesOrMinMaxVector) {
  23941. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23942. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23943. };
  23944. /**
  23945. * Merge the array of meshes into a single mesh for performance reasons.
  23946. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23947. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23948. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23949. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23950. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23951. */
  23952. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23953. if (disposeSource === void 0) { disposeSource = true; }
  23954. var index;
  23955. if (!allow32BitsIndices) {
  23956. var totalVertices = 0;
  23957. // Counting vertices
  23958. for (index = 0; index < meshes.length; index++) {
  23959. if (meshes[index]) {
  23960. totalVertices += meshes[index].getTotalVertices();
  23961. if (totalVertices > 65536) {
  23962. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23963. return null;
  23964. }
  23965. }
  23966. }
  23967. }
  23968. // Merge
  23969. var vertexData;
  23970. var otherVertexData;
  23971. var indiceArray = new Array();
  23972. var source;
  23973. for (index = 0; index < meshes.length; index++) {
  23974. if (meshes[index]) {
  23975. meshes[index].computeWorldMatrix(true);
  23976. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23977. otherVertexData.transform(meshes[index].getWorldMatrix());
  23978. if (vertexData) {
  23979. vertexData.merge(otherVertexData);
  23980. }
  23981. else {
  23982. vertexData = otherVertexData;
  23983. source = meshes[index];
  23984. }
  23985. if (subdivideWithSubMeshes) {
  23986. indiceArray.push(meshes[index].getTotalIndices());
  23987. }
  23988. }
  23989. }
  23990. if (!meshSubclass) {
  23991. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23992. }
  23993. vertexData.applyToMesh(meshSubclass);
  23994. // Setting properties
  23995. meshSubclass.material = source.material;
  23996. meshSubclass.checkCollisions = source.checkCollisions;
  23997. // Cleaning
  23998. if (disposeSource) {
  23999. for (index = 0; index < meshes.length; index++) {
  24000. if (meshes[index]) {
  24001. meshes[index].dispose();
  24002. }
  24003. }
  24004. }
  24005. // Subdivide
  24006. if (subdivideWithSubMeshes) {
  24007. //-- Suppresions du submesh global
  24008. meshSubclass.releaseSubMeshes();
  24009. index = 0;
  24010. var offset = 0;
  24011. //-- aplique la subdivision en fonction du tableau d'indices
  24012. while (index < indiceArray.length) {
  24013. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24014. offset += indiceArray[index];
  24015. index++;
  24016. }
  24017. }
  24018. return meshSubclass;
  24019. };
  24020. // Consts
  24021. Mesh._FRONTSIDE = 0;
  24022. Mesh._BACKSIDE = 1;
  24023. Mesh._DOUBLESIDE = 2;
  24024. Mesh._DEFAULTSIDE = 0;
  24025. Mesh._NO_CAP = 0;
  24026. Mesh._CAP_START = 1;
  24027. Mesh._CAP_END = 2;
  24028. Mesh._CAP_ALL = 3;
  24029. return Mesh;
  24030. }(BABYLON.AbstractMesh));
  24031. BABYLON.Mesh = Mesh;
  24032. })(BABYLON || (BABYLON = {}));
  24033. //# sourceMappingURL=babylon.mesh.js.map
  24034. var BABYLON;
  24035. (function (BABYLON) {
  24036. var BaseSubMesh = (function () {
  24037. function BaseSubMesh() {
  24038. }
  24039. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  24040. get: function () {
  24041. return this._materialEffect;
  24042. },
  24043. enumerable: true,
  24044. configurable: true
  24045. });
  24046. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  24047. if (this._materialEffect === effect) {
  24048. if (!effect) {
  24049. this._materialDefines = undefined;
  24050. }
  24051. return;
  24052. }
  24053. this._materialDefines = defines;
  24054. this._materialEffect = effect;
  24055. };
  24056. return BaseSubMesh;
  24057. }());
  24058. BABYLON.BaseSubMesh = BaseSubMesh;
  24059. var SubMesh = (function (_super) {
  24060. __extends(SubMesh, _super);
  24061. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24062. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24063. var _this = _super.call(this) || this;
  24064. _this.materialIndex = materialIndex;
  24065. _this.verticesStart = verticesStart;
  24066. _this.verticesCount = verticesCount;
  24067. _this.indexStart = indexStart;
  24068. _this.indexCount = indexCount;
  24069. _this._renderId = 0;
  24070. _this._mesh = mesh;
  24071. _this._renderingMesh = renderingMesh || mesh;
  24072. mesh.subMeshes.push(_this);
  24073. _this._trianglePlanes = [];
  24074. _this._id = mesh.subMeshes.length - 1;
  24075. if (createBoundingBox) {
  24076. _this.refreshBoundingInfo();
  24077. mesh.computeWorldMatrix(true);
  24078. }
  24079. return _this;
  24080. }
  24081. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24082. get: function () {
  24083. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24084. },
  24085. enumerable: true,
  24086. configurable: true
  24087. });
  24088. /**
  24089. * Returns the submesh BoudingInfo object.
  24090. */
  24091. SubMesh.prototype.getBoundingInfo = function () {
  24092. if (this.IsGlobal) {
  24093. return this._mesh.getBoundingInfo();
  24094. }
  24095. return this._boundingInfo;
  24096. };
  24097. /**
  24098. * Sets the submesh BoundingInfo.
  24099. * Return the SubMesh.
  24100. */
  24101. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24102. this._boundingInfo = boundingInfo;
  24103. return this;
  24104. };
  24105. /**
  24106. * Returns the mesh of the current submesh.
  24107. */
  24108. SubMesh.prototype.getMesh = function () {
  24109. return this._mesh;
  24110. };
  24111. /**
  24112. * Returns the rendering mesh of the submesh.
  24113. */
  24114. SubMesh.prototype.getRenderingMesh = function () {
  24115. return this._renderingMesh;
  24116. };
  24117. /**
  24118. * Returns the submesh material.
  24119. */
  24120. SubMesh.prototype.getMaterial = function () {
  24121. var rootMaterial = this._renderingMesh.material;
  24122. if (rootMaterial && rootMaterial.getSubMaterial) {
  24123. var multiMaterial = rootMaterial;
  24124. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24125. if (this._currentMaterial !== effectiveMaterial) {
  24126. this._currentMaterial = effectiveMaterial;
  24127. this._materialDefines = undefined;
  24128. }
  24129. return effectiveMaterial;
  24130. }
  24131. if (!rootMaterial) {
  24132. return this._mesh.getScene().defaultMaterial;
  24133. }
  24134. return rootMaterial;
  24135. };
  24136. // Methods
  24137. /**
  24138. * Sets a new updated BoundingInfo object to the submesh.
  24139. * Returns the SubMesh.
  24140. */
  24141. SubMesh.prototype.refreshBoundingInfo = function () {
  24142. this._lastColliderWorldVertices = null;
  24143. if (this.IsGlobal) {
  24144. return;
  24145. }
  24146. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24147. if (!data) {
  24148. this._boundingInfo = this._mesh._boundingInfo;
  24149. return;
  24150. }
  24151. var indices = this._renderingMesh.getIndices();
  24152. var extend;
  24153. //is this the only submesh?
  24154. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24155. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24156. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24157. }
  24158. else {
  24159. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24160. }
  24161. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24162. return this;
  24163. };
  24164. SubMesh.prototype._checkCollision = function (collider) {
  24165. return this.getBoundingInfo()._checkCollision(collider);
  24166. };
  24167. /**
  24168. * Updates the submesh BoundingInfo.
  24169. * Returns the Submesh.
  24170. */
  24171. SubMesh.prototype.updateBoundingInfo = function (world) {
  24172. if (!this.getBoundingInfo()) {
  24173. this.refreshBoundingInfo();
  24174. }
  24175. this.getBoundingInfo().update(world);
  24176. return this;
  24177. };
  24178. /**
  24179. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24180. * Boolean returned.
  24181. */
  24182. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24183. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24184. };
  24185. /**
  24186. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24187. * Boolean returned.
  24188. */
  24189. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24190. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24191. };
  24192. /**
  24193. * Renders the submesh.
  24194. * Returns it.
  24195. */
  24196. SubMesh.prototype.render = function (enableAlphaMode) {
  24197. this._renderingMesh.render(this, enableAlphaMode);
  24198. return this;
  24199. };
  24200. /**
  24201. * Returns a new Index Buffer.
  24202. * Type returned : WebGLBuffer.
  24203. */
  24204. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24205. if (!this._linesIndexBuffer) {
  24206. var linesIndices = [];
  24207. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24208. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24209. }
  24210. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24211. this.linesIndexCount = linesIndices.length;
  24212. }
  24213. return this._linesIndexBuffer;
  24214. };
  24215. /**
  24216. * True is the passed Ray intersects the submesh bounding box.
  24217. * Boolean returned.
  24218. */
  24219. SubMesh.prototype.canIntersects = function (ray) {
  24220. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24221. };
  24222. /**
  24223. * Returns an object IntersectionInfo.
  24224. */
  24225. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24226. var intersectInfo = null;
  24227. // LineMesh first as it's also a Mesh...
  24228. if (this._mesh instanceof BABYLON.LinesMesh) {
  24229. var lineMesh = this._mesh;
  24230. // Line test
  24231. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24232. var p0 = positions[indices[index]];
  24233. var p1 = positions[indices[index + 1]];
  24234. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24235. if (length < 0) {
  24236. continue;
  24237. }
  24238. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24239. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24240. if (fastCheck) {
  24241. break;
  24242. }
  24243. }
  24244. }
  24245. }
  24246. else {
  24247. // Triangles test
  24248. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24249. var p0 = positions[indices[index]];
  24250. var p1 = positions[indices[index + 1]];
  24251. var p2 = positions[indices[index + 2]];
  24252. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24253. if (currentIntersectInfo) {
  24254. if (currentIntersectInfo.distance < 0) {
  24255. continue;
  24256. }
  24257. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24258. intersectInfo = currentIntersectInfo;
  24259. intersectInfo.faceId = index / 3;
  24260. if (fastCheck) {
  24261. break;
  24262. }
  24263. }
  24264. }
  24265. }
  24266. }
  24267. return intersectInfo;
  24268. };
  24269. SubMesh.prototype._rebuild = function () {
  24270. if (this._linesIndexBuffer) {
  24271. this._linesIndexBuffer = null;
  24272. }
  24273. };
  24274. // Clone
  24275. /**
  24276. * Creates a new Submesh from the passed Mesh.
  24277. */
  24278. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24279. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24280. if (!this.IsGlobal) {
  24281. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24282. }
  24283. return result;
  24284. };
  24285. // Dispose
  24286. /**
  24287. * Disposes the Submesh.
  24288. * Returns nothing.
  24289. */
  24290. SubMesh.prototype.dispose = function () {
  24291. if (this._linesIndexBuffer) {
  24292. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24293. this._linesIndexBuffer = null;
  24294. }
  24295. // Remove from mesh
  24296. var index = this._mesh.subMeshes.indexOf(this);
  24297. this._mesh.subMeshes.splice(index, 1);
  24298. };
  24299. // Statics
  24300. /**
  24301. * Creates a new Submesh from the passed parameters :
  24302. * - materialIndex (integer) : the index of the main mesh material.
  24303. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24304. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24305. * - mesh (Mesh) : the main mesh to create the submesh from.
  24306. * - renderingMesh (optional Mesh) : rendering mesh.
  24307. */
  24308. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24309. var minVertexIndex = Number.MAX_VALUE;
  24310. var maxVertexIndex = -Number.MAX_VALUE;
  24311. renderingMesh = renderingMesh || mesh;
  24312. var indices = renderingMesh.getIndices();
  24313. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24314. var vertexIndex = indices[index];
  24315. if (vertexIndex < minVertexIndex)
  24316. minVertexIndex = vertexIndex;
  24317. if (vertexIndex > maxVertexIndex)
  24318. maxVertexIndex = vertexIndex;
  24319. }
  24320. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24321. };
  24322. return SubMesh;
  24323. }(BaseSubMesh));
  24324. BABYLON.SubMesh = SubMesh;
  24325. })(BABYLON || (BABYLON = {}));
  24326. //# sourceMappingURL=babylon.subMesh.js.map
  24327. var BABYLON;
  24328. (function (BABYLON) {
  24329. var EffectFallbacks = (function () {
  24330. function EffectFallbacks() {
  24331. this._defines = {};
  24332. this._currentRank = 32;
  24333. this._maxRank = -1;
  24334. }
  24335. EffectFallbacks.prototype.unBindMesh = function () {
  24336. this._mesh = null;
  24337. };
  24338. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24339. if (!this._defines[rank]) {
  24340. if (rank < this._currentRank) {
  24341. this._currentRank = rank;
  24342. }
  24343. if (rank > this._maxRank) {
  24344. this._maxRank = rank;
  24345. }
  24346. this._defines[rank] = new Array();
  24347. }
  24348. this._defines[rank].push(define);
  24349. };
  24350. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24351. this._meshRank = rank;
  24352. this._mesh = mesh;
  24353. if (rank < this._currentRank) {
  24354. this._currentRank = rank;
  24355. }
  24356. if (rank > this._maxRank) {
  24357. this._maxRank = rank;
  24358. }
  24359. };
  24360. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24361. get: function () {
  24362. return this._currentRank <= this._maxRank;
  24363. },
  24364. enumerable: true,
  24365. configurable: true
  24366. });
  24367. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24368. // First we try to switch to CPU skinning
  24369. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24370. this._mesh.computeBonesUsingShaders = false;
  24371. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24372. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24373. var scene = this._mesh.getScene();
  24374. for (var index = 0; index < scene.meshes.length; index++) {
  24375. var otherMesh = scene.meshes[index];
  24376. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24377. otherMesh.computeBonesUsingShaders = false;
  24378. }
  24379. }
  24380. }
  24381. else {
  24382. var currentFallbacks = this._defines[this._currentRank];
  24383. if (currentFallbacks) {
  24384. for (var index = 0; index < currentFallbacks.length; index++) {
  24385. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24386. }
  24387. }
  24388. this._currentRank++;
  24389. }
  24390. return currentDefines;
  24391. };
  24392. return EffectFallbacks;
  24393. }());
  24394. BABYLON.EffectFallbacks = EffectFallbacks;
  24395. var EffectCreationOptions = (function () {
  24396. function EffectCreationOptions() {
  24397. }
  24398. return EffectCreationOptions;
  24399. }());
  24400. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24401. var Effect = (function () {
  24402. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24403. var _this = this;
  24404. this.uniqueId = 0;
  24405. this.onCompileObservable = new BABYLON.Observable();
  24406. this.onErrorObservable = new BABYLON.Observable();
  24407. this.onBindObservable = new BABYLON.Observable();
  24408. this._uniformBuffersNames = {};
  24409. this._isReady = false;
  24410. this._compilationError = "";
  24411. this.name = baseName;
  24412. if (attributesNamesOrOptions.attributes) {
  24413. var options = attributesNamesOrOptions;
  24414. this._engine = uniformsNamesOrEngine;
  24415. this._attributesNames = options.attributes;
  24416. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24417. this._samplers = options.samplers;
  24418. this.defines = options.defines;
  24419. this.onError = options.onError;
  24420. this.onCompiled = options.onCompiled;
  24421. this._fallbacks = options.fallbacks;
  24422. this._indexParameters = options.indexParameters;
  24423. if (options.uniformBuffersNames) {
  24424. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24425. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24426. }
  24427. }
  24428. }
  24429. else {
  24430. this._engine = engine;
  24431. this.defines = defines;
  24432. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24433. this._samplers = samplers;
  24434. this._attributesNames = attributesNamesOrOptions;
  24435. this.onError = onError;
  24436. this.onCompiled = onCompiled;
  24437. this._indexParameters = indexParameters;
  24438. this._fallbacks = fallbacks;
  24439. }
  24440. this.uniqueId = Effect._uniqueIdSeed++;
  24441. var vertexSource;
  24442. var fragmentSource;
  24443. if (baseName.vertexElement) {
  24444. vertexSource = document.getElementById(baseName.vertexElement);
  24445. if (!vertexSource) {
  24446. vertexSource = baseName.vertexElement;
  24447. }
  24448. }
  24449. else {
  24450. vertexSource = baseName.vertex || baseName;
  24451. }
  24452. if (baseName.fragmentElement) {
  24453. fragmentSource = document.getElementById(baseName.fragmentElement);
  24454. if (!fragmentSource) {
  24455. fragmentSource = baseName.fragmentElement;
  24456. }
  24457. }
  24458. else {
  24459. fragmentSource = baseName.fragment || baseName;
  24460. }
  24461. this._loadVertexShader(vertexSource, function (vertexCode) {
  24462. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24463. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24464. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24465. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24466. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24467. if (baseName) {
  24468. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24469. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24470. }
  24471. else {
  24472. _this._vertexSourceCode = migratedVertexCode;
  24473. _this._fragmentSourceCode = migratedFragmentCode;
  24474. }
  24475. _this._prepareEffect();
  24476. });
  24477. });
  24478. });
  24479. });
  24480. });
  24481. });
  24482. }
  24483. Object.defineProperty(Effect.prototype, "key", {
  24484. get: function () {
  24485. return this._key;
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. // Properties
  24491. Effect.prototype.isReady = function () {
  24492. return this._isReady;
  24493. };
  24494. Effect.prototype.getEngine = function () {
  24495. return this._engine;
  24496. };
  24497. Effect.prototype.getProgram = function () {
  24498. return this._program;
  24499. };
  24500. Effect.prototype.getAttributesNames = function () {
  24501. return this._attributesNames;
  24502. };
  24503. Effect.prototype.getAttributeLocation = function (index) {
  24504. return this._attributes[index];
  24505. };
  24506. Effect.prototype.getAttributeLocationByName = function (name) {
  24507. var index = this._attributesNames.indexOf(name);
  24508. return this._attributes[index];
  24509. };
  24510. Effect.prototype.getAttributesCount = function () {
  24511. return this._attributes.length;
  24512. };
  24513. Effect.prototype.getUniformIndex = function (uniformName) {
  24514. return this._uniformsNames.indexOf(uniformName);
  24515. };
  24516. Effect.prototype.getUniform = function (uniformName) {
  24517. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24518. };
  24519. Effect.prototype.getSamplers = function () {
  24520. return this._samplers;
  24521. };
  24522. Effect.prototype.getCompilationError = function () {
  24523. return this._compilationError;
  24524. };
  24525. // Methods
  24526. Effect.prototype.executeWhenCompiled = function (func) {
  24527. if (this.isReady()) {
  24528. func(this);
  24529. return;
  24530. }
  24531. this.onCompileObservable.add(function (effect) {
  24532. func(effect);
  24533. });
  24534. };
  24535. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24536. // DOM element ?
  24537. if (vertex instanceof HTMLElement) {
  24538. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24539. callback(vertexCode);
  24540. return;
  24541. }
  24542. // Base64 encoded ?
  24543. if (vertex.substr(0, 7) === "base64:") {
  24544. var vertexBinary = window.atob(vertex.substr(7));
  24545. callback(vertexBinary);
  24546. return;
  24547. }
  24548. // Is in local store ?
  24549. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24550. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24551. return;
  24552. }
  24553. var vertexShaderUrl;
  24554. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24555. vertexShaderUrl = vertex;
  24556. }
  24557. else {
  24558. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24559. }
  24560. // Vertex shader
  24561. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24562. };
  24563. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24564. // DOM element ?
  24565. if (fragment instanceof HTMLElement) {
  24566. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24567. callback(fragmentCode);
  24568. return;
  24569. }
  24570. // Base64 encoded ?
  24571. if (fragment.substr(0, 7) === "base64:") {
  24572. var fragmentBinary = window.atob(fragment.substr(7));
  24573. callback(fragmentBinary);
  24574. return;
  24575. }
  24576. // Is in local store ?
  24577. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24578. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24579. return;
  24580. }
  24581. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24582. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24583. return;
  24584. }
  24585. var fragmentShaderUrl;
  24586. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24587. fragmentShaderUrl = fragment;
  24588. }
  24589. else {
  24590. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24591. }
  24592. // Fragment shader
  24593. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24594. };
  24595. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24596. // Rebuild shaders source code
  24597. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24598. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24599. vertexCode = prefix + vertexCode;
  24600. fragmentCode = prefix + fragmentCode;
  24601. // Number lines of shaders source code
  24602. var i = 2;
  24603. var regex = /\n/gm;
  24604. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24605. i = 2;
  24606. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24607. // Dump shaders name and formatted source code
  24608. if (this.name.vertexElement) {
  24609. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24610. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24611. }
  24612. else if (this.name.vertex) {
  24613. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24614. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24615. }
  24616. else {
  24617. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24618. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24619. }
  24620. };
  24621. ;
  24622. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24623. var preparedSourceCode = this._processPrecision(sourceCode);
  24624. if (this._engine.webGLVersion == 1) {
  24625. callback(preparedSourceCode);
  24626. return;
  24627. }
  24628. // Already converted
  24629. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24630. callback(preparedSourceCode.replace("#version 300 es", ""));
  24631. return;
  24632. }
  24633. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  24634. // Remove extensions
  24635. // #extension GL_OES_standard_derivatives : enable
  24636. // #extension GL_EXT_shader_texture_lod : enable
  24637. // #extension GL_EXT_frag_depth : enable
  24638. // #extension GL_EXT_draw_buffers : require
  24639. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  24640. var result = preparedSourceCode.replace(regex, "");
  24641. // Migrate to GLSL v300
  24642. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24643. result = result.replace(/attribute[ \t]/g, "in ");
  24644. result = result.replace(/[ \t]attribute/g, " in");
  24645. if (isFragment) {
  24646. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24647. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24648. result = result.replace(/texture2D\(/g, "texture(");
  24649. result = result.replace(/textureCube\(/g, "texture(");
  24650. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24651. result = result.replace(/gl_FragColor/g, "glFragColor");
  24652. result = result.replace(/gl_FragData/g, "glFragData");
  24653. result = result.replace(/void\s+?main\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  24654. }
  24655. callback(result);
  24656. };
  24657. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24658. var _this = this;
  24659. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24660. var match = regex.exec(sourceCode);
  24661. var returnValue = new String(sourceCode);
  24662. while (match != null) {
  24663. var includeFile = match[1];
  24664. // Uniform declaration
  24665. if (includeFile.indexOf("__decl__") !== -1) {
  24666. includeFile = includeFile.replace(/__decl__/, "");
  24667. if (this._engine.supportsUniformBuffers) {
  24668. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24669. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24670. }
  24671. includeFile = includeFile + "Declaration";
  24672. }
  24673. if (Effect.IncludesShadersStore[includeFile]) {
  24674. // Substitution
  24675. var includeContent = Effect.IncludesShadersStore[includeFile];
  24676. if (match[2]) {
  24677. var splits = match[3].split(",");
  24678. for (var index = 0; index < splits.length; index += 2) {
  24679. var source = new RegExp(splits[index], "g");
  24680. var dest = splits[index + 1];
  24681. includeContent = includeContent.replace(source, dest);
  24682. }
  24683. }
  24684. if (match[4]) {
  24685. var indexString = match[5];
  24686. if (indexString.indexOf("..") !== -1) {
  24687. var indexSplits = indexString.split("..");
  24688. var minIndex = parseInt(indexSplits[0]);
  24689. var maxIndex = parseInt(indexSplits[1]);
  24690. var sourceIncludeContent = includeContent.slice(0);
  24691. includeContent = "";
  24692. if (isNaN(maxIndex)) {
  24693. maxIndex = this._indexParameters[indexSplits[1]];
  24694. }
  24695. for (var i = minIndex; i < maxIndex; i++) {
  24696. if (!this._engine.supportsUniformBuffers) {
  24697. // Ubo replacement
  24698. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24699. return p1 + "{X}";
  24700. });
  24701. }
  24702. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24703. }
  24704. }
  24705. else {
  24706. if (!this._engine.supportsUniformBuffers) {
  24707. // Ubo replacement
  24708. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24709. return p1 + "{X}";
  24710. });
  24711. }
  24712. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24713. }
  24714. }
  24715. // Replace
  24716. returnValue = returnValue.replace(match[0], includeContent);
  24717. }
  24718. else {
  24719. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24720. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24721. Effect.IncludesShadersStore[includeFile] = fileContent;
  24722. _this._processIncludes(returnValue, callback);
  24723. });
  24724. return;
  24725. }
  24726. match = regex.exec(sourceCode);
  24727. }
  24728. callback(returnValue);
  24729. };
  24730. Effect.prototype._processPrecision = function (source) {
  24731. if (source.indexOf("precision highp float") === -1) {
  24732. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24733. source = "precision mediump float;\n" + source;
  24734. }
  24735. else {
  24736. source = "precision highp float;\n" + source;
  24737. }
  24738. }
  24739. else {
  24740. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24741. source = source.replace("precision highp float", "precision mediump float");
  24742. }
  24743. }
  24744. return source;
  24745. };
  24746. Effect.prototype._prepareEffect = function () {
  24747. var attributesNames = this._attributesNames;
  24748. var defines = this.defines;
  24749. var fallbacks = this._fallbacks;
  24750. this._valueCache = {};
  24751. try {
  24752. var engine = this._engine;
  24753. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24754. if (engine.webGLVersion > 1) {
  24755. for (var name in this._uniformBuffersNames) {
  24756. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24757. }
  24758. }
  24759. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24760. this._attributes = engine.getAttributes(this._program, attributesNames);
  24761. var index;
  24762. for (index = 0; index < this._samplers.length; index++) {
  24763. var sampler = this.getUniform(this._samplers[index]);
  24764. if (sampler == null) {
  24765. this._samplers.splice(index, 1);
  24766. index--;
  24767. }
  24768. }
  24769. engine.bindSamplers(this);
  24770. this._compilationError = "";
  24771. this._isReady = true;
  24772. if (this.onCompiled) {
  24773. this.onCompiled(this);
  24774. }
  24775. this.onCompileObservable.notifyObservers(this);
  24776. this.onCompileObservable.clear();
  24777. // Unbind mesh reference in fallbacks
  24778. if (this._fallbacks) {
  24779. this._fallbacks.unBindMesh();
  24780. }
  24781. }
  24782. catch (e) {
  24783. this._compilationError = e.message;
  24784. // Let's go through fallbacks then
  24785. BABYLON.Tools.Error("Unable to compile effect:");
  24786. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24787. return " " + uniform;
  24788. }));
  24789. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24790. return " " + attribute;
  24791. }));
  24792. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24793. BABYLON.Tools.Error("Error: " + this._compilationError);
  24794. if (fallbacks && fallbacks.isMoreFallbacks) {
  24795. BABYLON.Tools.Error("Trying next fallback.");
  24796. this.defines = fallbacks.reduce(this.defines);
  24797. this._prepareEffect();
  24798. }
  24799. else {
  24800. if (this.onError) {
  24801. this.onError(this, this._compilationError);
  24802. }
  24803. this.onErrorObservable.notifyObservers(this);
  24804. this.onErrorObservable.clear();
  24805. // Unbind mesh reference in fallbacks
  24806. if (this._fallbacks) {
  24807. this._fallbacks.unBindMesh();
  24808. }
  24809. }
  24810. }
  24811. };
  24812. Object.defineProperty(Effect.prototype, "isSupported", {
  24813. get: function () {
  24814. return this._compilationError === "";
  24815. },
  24816. enumerable: true,
  24817. configurable: true
  24818. });
  24819. Effect.prototype._bindTexture = function (channel, texture) {
  24820. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24821. };
  24822. Effect.prototype.setTexture = function (channel, texture) {
  24823. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24824. };
  24825. Effect.prototype.setTextureArray = function (channel, textures) {
  24826. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24827. var initialPos = this._samplers.indexOf(channel);
  24828. for (var index = 1; index < textures.length; index++) {
  24829. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24830. }
  24831. }
  24832. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24833. };
  24834. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24835. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24836. };
  24837. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24838. var cache = this._valueCache[uniformName];
  24839. var flag = matrix.updateFlag;
  24840. if (cache !== undefined && cache === flag) {
  24841. return false;
  24842. }
  24843. this._valueCache[uniformName] = flag;
  24844. return true;
  24845. };
  24846. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24847. var cache = this._valueCache[uniformName];
  24848. if (!cache) {
  24849. cache = [x, y];
  24850. this._valueCache[uniformName] = cache;
  24851. return true;
  24852. }
  24853. var changed = false;
  24854. if (cache[0] !== x) {
  24855. cache[0] = x;
  24856. changed = true;
  24857. }
  24858. if (cache[1] !== y) {
  24859. cache[1] = y;
  24860. changed = true;
  24861. }
  24862. return changed;
  24863. };
  24864. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24865. var cache = this._valueCache[uniformName];
  24866. if (!cache) {
  24867. cache = [x, y, z];
  24868. this._valueCache[uniformName] = cache;
  24869. return true;
  24870. }
  24871. var changed = false;
  24872. if (cache[0] !== x) {
  24873. cache[0] = x;
  24874. changed = true;
  24875. }
  24876. if (cache[1] !== y) {
  24877. cache[1] = y;
  24878. changed = true;
  24879. }
  24880. if (cache[2] !== z) {
  24881. cache[2] = z;
  24882. changed = true;
  24883. }
  24884. return changed;
  24885. };
  24886. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24887. var cache = this._valueCache[uniformName];
  24888. if (!cache) {
  24889. cache = [x, y, z, w];
  24890. this._valueCache[uniformName] = cache;
  24891. return true;
  24892. }
  24893. var changed = false;
  24894. if (cache[0] !== x) {
  24895. cache[0] = x;
  24896. changed = true;
  24897. }
  24898. if (cache[1] !== y) {
  24899. cache[1] = y;
  24900. changed = true;
  24901. }
  24902. if (cache[2] !== z) {
  24903. cache[2] = z;
  24904. changed = true;
  24905. }
  24906. if (cache[3] !== w) {
  24907. cache[3] = w;
  24908. changed = true;
  24909. }
  24910. return changed;
  24911. };
  24912. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24913. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24914. return;
  24915. }
  24916. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24917. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24918. };
  24919. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24920. this._engine.bindUniformBlock(this._program, blockName, index);
  24921. };
  24922. Effect.prototype.setIntArray = function (uniformName, array) {
  24923. this._valueCache[uniformName] = null;
  24924. this._engine.setIntArray(this.getUniform(uniformName), array);
  24925. return this;
  24926. };
  24927. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24928. this._valueCache[uniformName] = null;
  24929. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24930. return this;
  24931. };
  24932. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24933. this._valueCache[uniformName] = null;
  24934. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24935. return this;
  24936. };
  24937. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24938. this._valueCache[uniformName] = null;
  24939. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24940. return this;
  24941. };
  24942. Effect.prototype.setFloatArray = function (uniformName, array) {
  24943. this._valueCache[uniformName] = null;
  24944. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24945. return this;
  24946. };
  24947. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24948. this._valueCache[uniformName] = null;
  24949. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24950. return this;
  24951. };
  24952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24953. this._valueCache[uniformName] = null;
  24954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24955. return this;
  24956. };
  24957. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24958. this._valueCache[uniformName] = null;
  24959. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24960. return this;
  24961. };
  24962. Effect.prototype.setArray = function (uniformName, array) {
  24963. this._valueCache[uniformName] = null;
  24964. this._engine.setArray(this.getUniform(uniformName), array);
  24965. return this;
  24966. };
  24967. Effect.prototype.setArray2 = function (uniformName, array) {
  24968. this._valueCache[uniformName] = null;
  24969. this._engine.setArray2(this.getUniform(uniformName), array);
  24970. return this;
  24971. };
  24972. Effect.prototype.setArray3 = function (uniformName, array) {
  24973. this._valueCache[uniformName] = null;
  24974. this._engine.setArray3(this.getUniform(uniformName), array);
  24975. return this;
  24976. };
  24977. Effect.prototype.setArray4 = function (uniformName, array) {
  24978. this._valueCache[uniformName] = null;
  24979. this._engine.setArray4(this.getUniform(uniformName), array);
  24980. return this;
  24981. };
  24982. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24983. if (!matrices) {
  24984. return;
  24985. }
  24986. this._valueCache[uniformName] = null;
  24987. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24988. return this;
  24989. };
  24990. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24991. if (this._cacheMatrix(uniformName, matrix)) {
  24992. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24993. }
  24994. return this;
  24995. };
  24996. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24997. this._valueCache[uniformName] = null;
  24998. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24999. return this;
  25000. };
  25001. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25002. this._valueCache[uniformName] = null;
  25003. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25004. return this;
  25005. };
  25006. Effect.prototype.setFloat = function (uniformName, value) {
  25007. var cache = this._valueCache[uniformName];
  25008. if (cache !== undefined && cache === value)
  25009. return this;
  25010. this._valueCache[uniformName] = value;
  25011. this._engine.setFloat(this.getUniform(uniformName), value);
  25012. return this;
  25013. };
  25014. Effect.prototype.setBool = function (uniformName, bool) {
  25015. var cache = this._valueCache[uniformName];
  25016. if (cache !== undefined && cache === bool)
  25017. return this;
  25018. this._valueCache[uniformName] = bool;
  25019. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25020. return this;
  25021. };
  25022. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25023. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25024. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25025. }
  25026. return this;
  25027. };
  25028. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25029. if (this._cacheFloat2(uniformName, x, y)) {
  25030. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25031. }
  25032. return this;
  25033. };
  25034. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25035. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25036. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25037. }
  25038. return this;
  25039. };
  25040. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25041. if (this._cacheFloat3(uniformName, x, y, z)) {
  25042. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25043. }
  25044. return this;
  25045. };
  25046. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25047. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25048. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25049. }
  25050. return this;
  25051. };
  25052. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25053. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25054. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25055. }
  25056. return this;
  25057. };
  25058. Effect.prototype.setColor3 = function (uniformName, color3) {
  25059. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25060. this._engine.setColor3(this.getUniform(uniformName), color3);
  25061. }
  25062. return this;
  25063. };
  25064. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25065. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25066. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25067. }
  25068. return this;
  25069. };
  25070. Effect.ResetCache = function () {
  25071. Effect._baseCache = {};
  25072. };
  25073. Effect._uniqueIdSeed = 0;
  25074. Effect._baseCache = {};
  25075. // Statics
  25076. Effect.ShadersStore = {};
  25077. Effect.IncludesShadersStore = {};
  25078. return Effect;
  25079. }());
  25080. BABYLON.Effect = Effect;
  25081. })(BABYLON || (BABYLON = {}));
  25082. //# sourceMappingURL=babylon.effect.js.map
  25083. var BABYLON;
  25084. (function (BABYLON) {
  25085. var MaterialHelper = (function () {
  25086. function MaterialHelper() {
  25087. }
  25088. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  25089. defines._needUVs = true;
  25090. defines[key] = true;
  25091. if (texture.getTextureMatrix().isIdentity(true)) {
  25092. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  25093. if (texture.coordinatesIndex === 0) {
  25094. defines["MAINUV1"] = true;
  25095. }
  25096. else {
  25097. defines["MAINUV2"] = true;
  25098. }
  25099. }
  25100. else {
  25101. defines[key + "DIRECTUV"] = 0;
  25102. }
  25103. };
  25104. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  25105. var matrix = texture.getTextureMatrix();
  25106. if (!matrix.isIdentity(true)) {
  25107. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  25108. }
  25109. };
  25110. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  25111. if (defines._areMiscDirty) {
  25112. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  25113. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  25114. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  25115. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  25116. }
  25117. };
  25118. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25119. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25120. var changed = false;
  25121. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25122. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25123. changed = true;
  25124. }
  25125. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25126. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25127. changed = true;
  25128. }
  25129. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25130. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25131. changed = true;
  25132. }
  25133. if (defines["INSTANCES"] !== useInstances) {
  25134. defines["INSTANCES"] = useInstances;
  25135. changed = true;
  25136. }
  25137. if (changed) {
  25138. defines.markAsUnprocessed();
  25139. }
  25140. };
  25141. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25142. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25143. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25144. return false;
  25145. }
  25146. defines._normals = defines._needNormals;
  25147. defines._uvs = defines._needUVs;
  25148. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25149. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25150. defines["TANGENT"] = true;
  25151. }
  25152. if (defines._needUVs) {
  25153. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25154. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25155. }
  25156. else {
  25157. defines["UV1"] = false;
  25158. defines["UV2"] = false;
  25159. }
  25160. if (useVertexColor) {
  25161. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25162. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25163. }
  25164. if (useBones) {
  25165. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25166. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25167. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25168. }
  25169. else {
  25170. defines["NUM_BONE_INFLUENCERS"] = 0;
  25171. defines["BonesPerMesh"] = 0;
  25172. }
  25173. }
  25174. if (useMorphTargets) {
  25175. if (mesh.morphTargetManager) {
  25176. var manager = mesh.morphTargetManager;
  25177. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25178. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25179. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25180. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25181. }
  25182. else {
  25183. defines["MORPHTARGETS_TANGENT"] = false;
  25184. defines["MORPHTARGETS_NORMAL"] = false;
  25185. defines["MORPHTARGETS"] = false;
  25186. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25187. }
  25188. }
  25189. return true;
  25190. };
  25191. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25192. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25193. if (disableLighting === void 0) { disableLighting = false; }
  25194. if (!defines._areLightsDirty) {
  25195. return defines._needNormals;
  25196. }
  25197. var lightIndex = 0;
  25198. var needNormals = false;
  25199. var needRebuild = false;
  25200. var lightmapMode = false;
  25201. var shadowEnabled = false;
  25202. var specularEnabled = false;
  25203. if (scene.lightsEnabled && !disableLighting) {
  25204. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25205. var light = _a[_i];
  25206. needNormals = true;
  25207. if (defines["LIGHT" + lightIndex] === undefined) {
  25208. needRebuild = true;
  25209. }
  25210. defines["LIGHT" + lightIndex] = true;
  25211. defines["SPOTLIGHT" + lightIndex] = false;
  25212. defines["HEMILIGHT" + lightIndex] = false;
  25213. defines["POINTLIGHT" + lightIndex] = false;
  25214. defines["DIRLIGHT" + lightIndex] = false;
  25215. var type;
  25216. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25217. type = "SPOTLIGHT" + lightIndex;
  25218. }
  25219. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25220. type = "HEMILIGHT" + lightIndex;
  25221. }
  25222. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25223. type = "POINTLIGHT" + lightIndex;
  25224. }
  25225. else {
  25226. type = "DIRLIGHT" + lightIndex;
  25227. }
  25228. defines[type] = true;
  25229. // Specular
  25230. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25231. specularEnabled = true;
  25232. }
  25233. // Shadows
  25234. defines["SHADOW" + lightIndex] = false;
  25235. defines["SHADOWPCF" + lightIndex] = false;
  25236. defines["SHADOWESM" + lightIndex] = false;
  25237. defines["SHADOWCUBE" + lightIndex] = false;
  25238. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25239. var shadowGenerator = light.getShadowGenerator();
  25240. if (shadowGenerator) {
  25241. shadowEnabled = true;
  25242. shadowGenerator.prepareDefines(defines, lightIndex);
  25243. }
  25244. }
  25245. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25246. lightmapMode = true;
  25247. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25248. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25249. }
  25250. else {
  25251. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25252. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25253. }
  25254. lightIndex++;
  25255. if (lightIndex === maxSimultaneousLights)
  25256. break;
  25257. }
  25258. }
  25259. defines["SPECULARTERM"] = specularEnabled;
  25260. defines["SHADOWS"] = shadowEnabled;
  25261. // Resetting all other lights if any
  25262. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25263. if (defines["LIGHT" + index] !== undefined) {
  25264. defines["LIGHT" + index] = false;
  25265. defines["HEMILIGHT" + lightIndex] = false;
  25266. defines["POINTLIGHT" + lightIndex] = false;
  25267. defines["DIRLIGHT" + lightIndex] = false;
  25268. defines["SPOTLIGHT" + lightIndex] = false;
  25269. defines["SHADOW" + lightIndex] = false;
  25270. }
  25271. }
  25272. var caps = scene.getEngine().getCaps();
  25273. if (defines["SHADOWFLOAT"] === undefined) {
  25274. needRebuild = true;
  25275. }
  25276. defines["SHADOWFLOAT"] = shadowEnabled &&
  25277. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25278. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25279. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25280. if (needRebuild) {
  25281. defines.rebuild();
  25282. }
  25283. return needNormals;
  25284. };
  25285. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25286. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25287. var uniformsList, uniformBuffersList, samplersList, defines;
  25288. if (uniformsListOrOptions.uniformsNames) {
  25289. var options = uniformsListOrOptions;
  25290. uniformsList = options.uniformsNames;
  25291. uniformBuffersList = options.uniformBuffersNames;
  25292. samplersList = options.samplers;
  25293. defines = options.defines;
  25294. maxSimultaneousLights = options.maxSimultaneousLights;
  25295. }
  25296. else {
  25297. uniformsList = uniformsListOrOptions;
  25298. }
  25299. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25300. if (!defines["LIGHT" + lightIndex]) {
  25301. break;
  25302. }
  25303. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25304. if (uniformBuffersList) {
  25305. uniformBuffersList.push("Light" + lightIndex);
  25306. }
  25307. samplersList.push("shadowSampler" + lightIndex);
  25308. }
  25309. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25310. uniformsList.push("morphTargetInfluences");
  25311. }
  25312. };
  25313. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25314. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25315. if (!defines["SHADOWS"]) {
  25316. return;
  25317. }
  25318. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25319. if (!defines["LIGHT" + lightIndex]) {
  25320. break;
  25321. }
  25322. if (lightIndex > 0) {
  25323. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25324. }
  25325. if (defines["SHADOW" + lightIndex]) {
  25326. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25327. }
  25328. if (defines["SHADOWPCF" + lightIndex]) {
  25329. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25330. }
  25331. if (defines["SHADOWESM" + lightIndex]) {
  25332. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25333. }
  25334. }
  25335. };
  25336. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25337. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25338. if (influencers > 0) {
  25339. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25340. var manager = mesh.morphTargetManager;
  25341. var normal = manager.supportsNormals && defines["NORMAL"];
  25342. var tangent = manager.supportsTangents && defines["TANGENT"];
  25343. for (var index = 0; index < influencers; index++) {
  25344. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25345. if (normal) {
  25346. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25347. }
  25348. if (tangent) {
  25349. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25350. }
  25351. if (attribs.length > maxAttributesCount) {
  25352. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25353. }
  25354. }
  25355. }
  25356. };
  25357. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25358. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25359. fallbacks.addCPUSkinningFallback(0, mesh);
  25360. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25361. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25362. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25365. }
  25366. }
  25367. };
  25368. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25369. if (defines["INSTANCES"]) {
  25370. attribs.push("world0");
  25371. attribs.push("world1");
  25372. attribs.push("world2");
  25373. attribs.push("world3");
  25374. }
  25375. };
  25376. // Bindings
  25377. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25378. if (light.shadowEnabled && mesh.receiveShadows) {
  25379. var shadowGenerator = light.getShadowGenerator();
  25380. if (shadowGenerator) {
  25381. shadowGenerator.bindShadowLight(lightIndex, effect);
  25382. }
  25383. }
  25384. };
  25385. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25386. light.transferToEffect(effect, lightIndex + "");
  25387. };
  25388. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25389. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25390. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25391. var lightIndex = 0;
  25392. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25393. var light = _a[_i];
  25394. var scaledIntensity = light.getScaledIntensity();
  25395. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25396. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25397. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25398. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25399. if (defines["SPECULARTERM"]) {
  25400. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25401. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25402. }
  25403. // Shadows
  25404. if (scene.shadowsEnabled) {
  25405. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25406. }
  25407. light._uniformBuffer.update();
  25408. lightIndex++;
  25409. if (lightIndex === maxSimultaneousLights)
  25410. break;
  25411. }
  25412. };
  25413. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25414. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25415. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25416. effect.setColor3("vFogColor", scene.fogColor);
  25417. }
  25418. };
  25419. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25420. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25421. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25422. if (matrices) {
  25423. effect.setMatrices("mBones", matrices);
  25424. }
  25425. }
  25426. };
  25427. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25428. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25429. return;
  25430. }
  25431. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25432. };
  25433. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25434. if (defines["LOGARITHMICDEPTH"]) {
  25435. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25436. }
  25437. };
  25438. MaterialHelper.BindClipPlane = function (effect, scene) {
  25439. if (scene.clipPlane) {
  25440. var clipPlane = scene.clipPlane;
  25441. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25442. }
  25443. };
  25444. return MaterialHelper;
  25445. }());
  25446. BABYLON.MaterialHelper = MaterialHelper;
  25447. })(BABYLON || (BABYLON = {}));
  25448. //# sourceMappingURL=babylon.materialHelper.js.map
  25449. var BABYLON;
  25450. (function (BABYLON) {
  25451. var MaterialDefines = (function () {
  25452. function MaterialDefines() {
  25453. this._isDirty = true;
  25454. this._areLightsDirty = true;
  25455. this._areAttributesDirty = true;
  25456. this._areTexturesDirty = true;
  25457. this._areFresnelDirty = true;
  25458. this._areMiscDirty = true;
  25459. this._areImageProcessingDirty = true;
  25460. this._normals = false;
  25461. this._uvs = false;
  25462. this._needNormals = false;
  25463. this._needUVs = false;
  25464. }
  25465. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25466. get: function () {
  25467. return this._isDirty;
  25468. },
  25469. enumerable: true,
  25470. configurable: true
  25471. });
  25472. MaterialDefines.prototype.markAsProcessed = function () {
  25473. this._isDirty = false;
  25474. this._areAttributesDirty = false;
  25475. this._areTexturesDirty = false;
  25476. this._areFresnelDirty = false;
  25477. this._areLightsDirty = false;
  25478. this._areMiscDirty = false;
  25479. this._areImageProcessingDirty = false;
  25480. };
  25481. MaterialDefines.prototype.markAsUnprocessed = function () {
  25482. this._isDirty = true;
  25483. };
  25484. MaterialDefines.prototype.markAllAsDirty = function () {
  25485. this._areTexturesDirty = true;
  25486. this._areAttributesDirty = true;
  25487. this._areLightsDirty = true;
  25488. this._areFresnelDirty = true;
  25489. this._areMiscDirty = true;
  25490. this._areImageProcessingDirty = true;
  25491. this._isDirty = true;
  25492. };
  25493. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25494. this._areImageProcessingDirty = true;
  25495. this._isDirty = true;
  25496. };
  25497. MaterialDefines.prototype.markAsLightDirty = function () {
  25498. this._areLightsDirty = true;
  25499. this._isDirty = true;
  25500. };
  25501. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25502. this._areAttributesDirty = true;
  25503. this._isDirty = true;
  25504. };
  25505. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25506. this._areTexturesDirty = true;
  25507. this._isDirty = true;
  25508. };
  25509. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25510. this._areFresnelDirty = true;
  25511. this._isDirty = true;
  25512. };
  25513. MaterialDefines.prototype.markAsMiscDirty = function () {
  25514. this._areMiscDirty = true;
  25515. this._isDirty = true;
  25516. };
  25517. MaterialDefines.prototype.rebuild = function () {
  25518. if (this._keys) {
  25519. delete this._keys;
  25520. }
  25521. this._keys = [];
  25522. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25523. var key = _a[_i];
  25524. if (key[0] === "_") {
  25525. continue;
  25526. }
  25527. this._keys.push(key);
  25528. }
  25529. };
  25530. MaterialDefines.prototype.isEqual = function (other) {
  25531. if (this._keys.length !== other._keys.length) {
  25532. return false;
  25533. }
  25534. for (var index = 0; index < this._keys.length; index++) {
  25535. var prop = this._keys[index];
  25536. if (this[prop] !== other[prop]) {
  25537. return false;
  25538. }
  25539. }
  25540. return true;
  25541. };
  25542. MaterialDefines.prototype.cloneTo = function (other) {
  25543. if (this._keys.length !== other._keys.length) {
  25544. other._keys = this._keys.slice(0);
  25545. }
  25546. for (var index = 0; index < this._keys.length; index++) {
  25547. var prop = this._keys[index];
  25548. other[prop] = this[prop];
  25549. }
  25550. };
  25551. MaterialDefines.prototype.reset = function () {
  25552. for (var index = 0; index < this._keys.length; index++) {
  25553. var prop = this._keys[index];
  25554. if (typeof (this[prop]) === "number") {
  25555. this[prop] = 0;
  25556. }
  25557. else {
  25558. this[prop] = false;
  25559. }
  25560. }
  25561. };
  25562. MaterialDefines.prototype.toString = function () {
  25563. var result = "";
  25564. for (var index = 0; index < this._keys.length; index++) {
  25565. var prop = this._keys[index];
  25566. var value = this[prop];
  25567. if (typeof (value) === "number") {
  25568. result += "#define " + prop + " " + this[prop] + "\n";
  25569. }
  25570. else if (value) {
  25571. result += "#define " + prop + "\n";
  25572. }
  25573. }
  25574. return result;
  25575. };
  25576. return MaterialDefines;
  25577. }());
  25578. BABYLON.MaterialDefines = MaterialDefines;
  25579. var Material = (function () {
  25580. function Material(name, scene, doNotAdd) {
  25581. this.checkReadyOnEveryCall = false;
  25582. this.checkReadyOnlyOnce = false;
  25583. this.state = "";
  25584. this.alpha = 1.0;
  25585. this._backFaceCulling = true;
  25586. this.doNotSerialize = false;
  25587. this.storeEffectOnSubMeshes = false;
  25588. /**
  25589. * An event triggered when the material is disposed.
  25590. * @type {BABYLON.Observable}
  25591. */
  25592. this.onDisposeObservable = new BABYLON.Observable();
  25593. /**
  25594. * An event triggered when the material is bound.
  25595. * @type {BABYLON.Observable}
  25596. */
  25597. this.onBindObservable = new BABYLON.Observable();
  25598. /**
  25599. * An event triggered when the material is unbound.
  25600. * @type {BABYLON.Observable}
  25601. */
  25602. this.onUnBindObservable = new BABYLON.Observable();
  25603. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25604. this.needDepthPrePass = false;
  25605. this.disableDepthWrite = false;
  25606. this._fogEnabled = true;
  25607. this.pointSize = 1.0;
  25608. this.zOffset = 0;
  25609. this._wasPreviouslyReady = false;
  25610. this._fillMode = Material.TriangleFillMode;
  25611. this.name = name;
  25612. this.id = name || BABYLON.Tools.RandomId();
  25613. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25614. if (this._scene.useRightHandedSystem) {
  25615. this.sideOrientation = Material.ClockWiseSideOrientation;
  25616. }
  25617. else {
  25618. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25619. }
  25620. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25621. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25622. if (!doNotAdd) {
  25623. this._scene.materials.push(this);
  25624. }
  25625. }
  25626. Object.defineProperty(Material, "TriangleFillMode", {
  25627. get: function () {
  25628. return Material._TriangleFillMode;
  25629. },
  25630. enumerable: true,
  25631. configurable: true
  25632. });
  25633. Object.defineProperty(Material, "WireFrameFillMode", {
  25634. get: function () {
  25635. return Material._WireFrameFillMode;
  25636. },
  25637. enumerable: true,
  25638. configurable: true
  25639. });
  25640. Object.defineProperty(Material, "PointFillMode", {
  25641. get: function () {
  25642. return Material._PointFillMode;
  25643. },
  25644. enumerable: true,
  25645. configurable: true
  25646. });
  25647. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25648. get: function () {
  25649. return Material._ClockWiseSideOrientation;
  25650. },
  25651. enumerable: true,
  25652. configurable: true
  25653. });
  25654. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25655. get: function () {
  25656. return Material._CounterClockWiseSideOrientation;
  25657. },
  25658. enumerable: true,
  25659. configurable: true
  25660. });
  25661. Object.defineProperty(Material, "TextureDirtyFlag", {
  25662. get: function () {
  25663. return Material._TextureDirtyFlag;
  25664. },
  25665. enumerable: true,
  25666. configurable: true
  25667. });
  25668. Object.defineProperty(Material, "LightDirtyFlag", {
  25669. get: function () {
  25670. return Material._LightDirtyFlag;
  25671. },
  25672. enumerable: true,
  25673. configurable: true
  25674. });
  25675. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25676. get: function () {
  25677. return Material._FresnelDirtyFlag;
  25678. },
  25679. enumerable: true,
  25680. configurable: true
  25681. });
  25682. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25683. get: function () {
  25684. return Material._AttributesDirtyFlag;
  25685. },
  25686. enumerable: true,
  25687. configurable: true
  25688. });
  25689. Object.defineProperty(Material, "MiscDirtyFlag", {
  25690. get: function () {
  25691. return Material._MiscDirtyFlag;
  25692. },
  25693. enumerable: true,
  25694. configurable: true
  25695. });
  25696. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25697. get: function () {
  25698. return this._backFaceCulling;
  25699. },
  25700. set: function (value) {
  25701. if (this._backFaceCulling === value) {
  25702. return;
  25703. }
  25704. this._backFaceCulling = value;
  25705. this.markAsDirty(Material.TextureDirtyFlag);
  25706. },
  25707. enumerable: true,
  25708. configurable: true
  25709. });
  25710. Object.defineProperty(Material.prototype, "onDispose", {
  25711. set: function (callback) {
  25712. if (this._onDisposeObserver) {
  25713. this.onDisposeObservable.remove(this._onDisposeObserver);
  25714. }
  25715. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25716. },
  25717. enumerable: true,
  25718. configurable: true
  25719. });
  25720. Object.defineProperty(Material.prototype, "onBind", {
  25721. set: function (callback) {
  25722. if (this._onBindObserver) {
  25723. this.onBindObservable.remove(this._onBindObserver);
  25724. }
  25725. this._onBindObserver = this.onBindObservable.add(callback);
  25726. },
  25727. enumerable: true,
  25728. configurable: true
  25729. });
  25730. Object.defineProperty(Material.prototype, "fogEnabled", {
  25731. get: function () {
  25732. return this._fogEnabled;
  25733. },
  25734. set: function (value) {
  25735. if (this._fogEnabled === value) {
  25736. return;
  25737. }
  25738. this._fogEnabled = value;
  25739. this.markAsDirty(Material.MiscDirtyFlag);
  25740. },
  25741. enumerable: true,
  25742. configurable: true
  25743. });
  25744. Object.defineProperty(Material.prototype, "wireframe", {
  25745. get: function () {
  25746. return this._fillMode === Material.WireFrameFillMode;
  25747. },
  25748. set: function (value) {
  25749. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25750. },
  25751. enumerable: true,
  25752. configurable: true
  25753. });
  25754. Object.defineProperty(Material.prototype, "pointsCloud", {
  25755. get: function () {
  25756. return this._fillMode === Material.PointFillMode;
  25757. },
  25758. set: function (value) {
  25759. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25760. },
  25761. enumerable: true,
  25762. configurable: true
  25763. });
  25764. Object.defineProperty(Material.prototype, "fillMode", {
  25765. get: function () {
  25766. return this._fillMode;
  25767. },
  25768. set: function (value) {
  25769. if (this._fillMode === value) {
  25770. return;
  25771. }
  25772. this._fillMode = value;
  25773. this.markAsDirty(Material.MiscDirtyFlag);
  25774. },
  25775. enumerable: true,
  25776. configurable: true
  25777. });
  25778. /**
  25779. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25780. * subclasses should override adding information pertainent to themselves
  25781. */
  25782. Material.prototype.toString = function (fullDetails) {
  25783. var ret = "Name: " + this.name;
  25784. if (fullDetails) {
  25785. }
  25786. return ret;
  25787. };
  25788. /**
  25789. * Child classes can use it to update shaders
  25790. */
  25791. Material.prototype.getClassName = function () {
  25792. return "Material";
  25793. };
  25794. Object.defineProperty(Material.prototype, "isFrozen", {
  25795. get: function () {
  25796. return this.checkReadyOnlyOnce;
  25797. },
  25798. enumerable: true,
  25799. configurable: true
  25800. });
  25801. Material.prototype.freeze = function () {
  25802. this.checkReadyOnlyOnce = true;
  25803. };
  25804. Material.prototype.unfreeze = function () {
  25805. this.checkReadyOnlyOnce = false;
  25806. };
  25807. Material.prototype.isReady = function (mesh, useInstances) {
  25808. return true;
  25809. };
  25810. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25811. return false;
  25812. };
  25813. Material.prototype.getEffect = function () {
  25814. return this._effect;
  25815. };
  25816. Material.prototype.getScene = function () {
  25817. return this._scene;
  25818. };
  25819. Material.prototype.needAlphaBlending = function () {
  25820. return (this.alpha < 1.0);
  25821. };
  25822. Material.prototype.needAlphaTesting = function () {
  25823. return false;
  25824. };
  25825. Material.prototype.getAlphaTestTexture = function () {
  25826. return null;
  25827. };
  25828. Material.prototype.markDirty = function () {
  25829. this._wasPreviouslyReady = false;
  25830. };
  25831. Material.prototype._preBind = function (effect) {
  25832. var engine = this._scene.getEngine();
  25833. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25834. engine.enableEffect(effect ? effect : this._effect);
  25835. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25836. };
  25837. Material.prototype.bind = function (world, mesh) {
  25838. };
  25839. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25840. };
  25841. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25842. };
  25843. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25844. sceneUbo.bindToEffect(effect, "Scene");
  25845. };
  25846. Material.prototype.bindView = function (effect) {
  25847. if (!this._useUBO) {
  25848. effect.setMatrix("view", this.getScene().getViewMatrix());
  25849. }
  25850. else {
  25851. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25852. }
  25853. };
  25854. Material.prototype.bindViewProjection = function (effect) {
  25855. if (!this._useUBO) {
  25856. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25857. }
  25858. else {
  25859. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25860. }
  25861. };
  25862. Material.prototype._afterBind = function (mesh) {
  25863. this._scene._cachedMaterial = this;
  25864. if (mesh) {
  25865. this._scene._cachedVisibility = mesh.visibility;
  25866. }
  25867. else {
  25868. this._scene._cachedVisibility = 1;
  25869. }
  25870. this.onBindObservable.notifyObservers(mesh);
  25871. if (this.disableDepthWrite) {
  25872. var engine = this._scene.getEngine();
  25873. this._cachedDepthWriteState = engine.getDepthWrite();
  25874. engine.setDepthWrite(false);
  25875. }
  25876. };
  25877. Material.prototype.unbind = function () {
  25878. this.onUnBindObservable.notifyObservers(this);
  25879. if (this.disableDepthWrite) {
  25880. var engine = this._scene.getEngine();
  25881. engine.setDepthWrite(this._cachedDepthWriteState);
  25882. }
  25883. };
  25884. Material.prototype.getActiveTextures = function () {
  25885. return [];
  25886. };
  25887. Material.prototype.hasTexture = function (texture) {
  25888. return false;
  25889. };
  25890. Material.prototype.clone = function (name) {
  25891. return null;
  25892. };
  25893. Material.prototype.getBindedMeshes = function () {
  25894. var result = new Array();
  25895. for (var index = 0; index < this._scene.meshes.length; index++) {
  25896. var mesh = this._scene.meshes[index];
  25897. if (mesh.material === this) {
  25898. result.push(mesh);
  25899. }
  25900. }
  25901. return result;
  25902. };
  25903. /**
  25904. * Force shader compilation including textures ready check
  25905. */
  25906. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25907. var _this = this;
  25908. var subMesh = new BABYLON.BaseSubMesh();
  25909. var scene = this.getScene();
  25910. var engine = scene.getEngine();
  25911. var checkReady = function () {
  25912. if (!_this._scene || !_this._scene.getEngine()) {
  25913. return;
  25914. }
  25915. if (subMesh._materialDefines) {
  25916. subMesh._materialDefines._renderId = -1;
  25917. }
  25918. var alphaTestState = engine.getAlphaTesting();
  25919. var clipPlaneState = scene.clipPlane;
  25920. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25921. if (options && options.clipPlane) {
  25922. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25923. }
  25924. if (_this.storeEffectOnSubMeshes) {
  25925. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25926. if (onCompiled) {
  25927. onCompiled(_this);
  25928. }
  25929. }
  25930. else {
  25931. setTimeout(checkReady, 16);
  25932. }
  25933. }
  25934. else {
  25935. if (_this.isReady(mesh)) {
  25936. if (onCompiled) {
  25937. onCompiled(_this);
  25938. }
  25939. }
  25940. else {
  25941. setTimeout(checkReady, 16);
  25942. }
  25943. }
  25944. engine.setAlphaTesting(alphaTestState);
  25945. if (options && options.clipPlane) {
  25946. scene.clipPlane = clipPlaneState;
  25947. }
  25948. };
  25949. checkReady();
  25950. };
  25951. Material.prototype.markAsDirty = function (flag) {
  25952. if (flag & Material.TextureDirtyFlag) {
  25953. this._markAllSubMeshesAsTexturesDirty();
  25954. }
  25955. if (flag & Material.LightDirtyFlag) {
  25956. this._markAllSubMeshesAsLightsDirty();
  25957. }
  25958. if (flag & Material.FresnelDirtyFlag) {
  25959. this._markAllSubMeshesAsFresnelDirty();
  25960. }
  25961. if (flag & Material.AttributesDirtyFlag) {
  25962. this._markAllSubMeshesAsAttributesDirty();
  25963. }
  25964. if (flag & Material.MiscDirtyFlag) {
  25965. this._markAllSubMeshesAsMiscDirty();
  25966. }
  25967. this.getScene().resetCachedMaterial();
  25968. };
  25969. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25970. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25971. var mesh = _a[_i];
  25972. if (!mesh.subMeshes) {
  25973. continue;
  25974. }
  25975. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25976. var subMesh = _c[_b];
  25977. if (subMesh.getMaterial() !== this) {
  25978. continue;
  25979. }
  25980. if (!subMesh._materialDefines) {
  25981. continue;
  25982. }
  25983. func(subMesh._materialDefines);
  25984. }
  25985. }
  25986. };
  25987. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25988. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25989. };
  25990. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25991. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25992. };
  25993. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25994. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25995. };
  25996. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25997. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25998. };
  25999. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  26000. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  26001. };
  26002. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  26003. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  26004. };
  26005. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26006. // Animations
  26007. this.getScene().stopAnimation(this);
  26008. // Remove from scene
  26009. var index = this._scene.materials.indexOf(this);
  26010. if (index >= 0) {
  26011. this._scene.materials.splice(index, 1);
  26012. }
  26013. // Remove from meshes
  26014. for (index = 0; index < this._scene.meshes.length; index++) {
  26015. var mesh = this._scene.meshes[index];
  26016. if (mesh.material === this) {
  26017. mesh.material = null;
  26018. if (mesh.geometry) {
  26019. var geometry = mesh.geometry;
  26020. if (this.storeEffectOnSubMeshes) {
  26021. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  26022. var subMesh = _a[_i];
  26023. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  26024. }
  26025. }
  26026. else {
  26027. geometry._releaseVertexArrayObject(this._effect);
  26028. }
  26029. }
  26030. }
  26031. }
  26032. this._uniformBuffer.dispose();
  26033. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26034. if (forceDisposeEffect && this._effect) {
  26035. if (this.storeEffectOnSubMeshes) {
  26036. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26037. var subMesh = _c[_b];
  26038. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  26039. }
  26040. }
  26041. else {
  26042. this._scene.getEngine()._releaseEffect(this._effect);
  26043. }
  26044. this._effect = null;
  26045. }
  26046. // Callback
  26047. this.onDisposeObservable.notifyObservers(this);
  26048. this.onDisposeObservable.clear();
  26049. this.onBindObservable.clear();
  26050. this.onUnBindObservable.clear();
  26051. };
  26052. Material.prototype.serialize = function () {
  26053. return BABYLON.SerializationHelper.Serialize(this);
  26054. };
  26055. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26056. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26057. multiMaterial.id = parsedMultiMaterial.id;
  26058. if (BABYLON.Tags) {
  26059. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26060. }
  26061. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26062. var subMatId = parsedMultiMaterial.materials[matIndex];
  26063. if (subMatId) {
  26064. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26065. }
  26066. else {
  26067. multiMaterial.subMaterials.push(null);
  26068. }
  26069. }
  26070. return multiMaterial;
  26071. };
  26072. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26073. if (!parsedMaterial.customType) {
  26074. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26075. }
  26076. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  26077. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  26078. if (!BABYLON.LegacyPBRMaterial) {
  26079. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  26080. return;
  26081. }
  26082. }
  26083. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26084. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26085. ;
  26086. };
  26087. Material._TriangleFillMode = 0;
  26088. Material._WireFrameFillMode = 1;
  26089. Material._PointFillMode = 2;
  26090. Material._ClockWiseSideOrientation = 0;
  26091. Material._CounterClockWiseSideOrientation = 1;
  26092. Material._TextureDirtyFlag = 1;
  26093. Material._LightDirtyFlag = 2;
  26094. Material._FresnelDirtyFlag = 4;
  26095. Material._AttributesDirtyFlag = 8;
  26096. Material._MiscDirtyFlag = 16;
  26097. __decorate([
  26098. BABYLON.serialize()
  26099. ], Material.prototype, "id", void 0);
  26100. __decorate([
  26101. BABYLON.serialize()
  26102. ], Material.prototype, "name", void 0);
  26103. __decorate([
  26104. BABYLON.serialize()
  26105. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26106. __decorate([
  26107. BABYLON.serialize()
  26108. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26109. __decorate([
  26110. BABYLON.serialize()
  26111. ], Material.prototype, "state", void 0);
  26112. __decorate([
  26113. BABYLON.serialize()
  26114. ], Material.prototype, "alpha", void 0);
  26115. __decorate([
  26116. BABYLON.serialize("backFaceCulling")
  26117. ], Material.prototype, "_backFaceCulling", void 0);
  26118. __decorate([
  26119. BABYLON.serialize()
  26120. ], Material.prototype, "sideOrientation", void 0);
  26121. __decorate([
  26122. BABYLON.serialize()
  26123. ], Material.prototype, "alphaMode", void 0);
  26124. __decorate([
  26125. BABYLON.serialize()
  26126. ], Material.prototype, "needDepthPrePass", void 0);
  26127. __decorate([
  26128. BABYLON.serialize()
  26129. ], Material.prototype, "disableDepthWrite", void 0);
  26130. __decorate([
  26131. BABYLON.serialize("fogEnabled")
  26132. ], Material.prototype, "_fogEnabled", void 0);
  26133. __decorate([
  26134. BABYLON.serialize()
  26135. ], Material.prototype, "pointSize", void 0);
  26136. __decorate([
  26137. BABYLON.serialize()
  26138. ], Material.prototype, "zOffset", void 0);
  26139. __decorate([
  26140. BABYLON.serialize()
  26141. ], Material.prototype, "wireframe", null);
  26142. __decorate([
  26143. BABYLON.serialize()
  26144. ], Material.prototype, "pointsCloud", null);
  26145. __decorate([
  26146. BABYLON.serialize()
  26147. ], Material.prototype, "fillMode", null);
  26148. return Material;
  26149. }());
  26150. BABYLON.Material = Material;
  26151. })(BABYLON || (BABYLON = {}));
  26152. //# sourceMappingURL=babylon.material.js.map
  26153. var BABYLON;
  26154. (function (BABYLON) {
  26155. var UniformBuffer = (function () {
  26156. /**
  26157. * Uniform buffer objects.
  26158. *
  26159. * Handles blocks of uniform on the GPU.
  26160. *
  26161. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26162. *
  26163. * For more information, please refer to :
  26164. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26165. */
  26166. function UniformBuffer(engine, data, dynamic) {
  26167. this._engine = engine;
  26168. this._noUBO = !engine.supportsUniformBuffers;
  26169. this._dynamic = dynamic;
  26170. this._data = data || [];
  26171. this._uniformLocations = {};
  26172. this._uniformSizes = {};
  26173. this._uniformLocationPointer = 0;
  26174. this._needSync = false;
  26175. if (this._noUBO) {
  26176. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26177. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26178. this.updateFloat = this._updateFloatForEffect;
  26179. this.updateFloat2 = this._updateFloat2ForEffect;
  26180. this.updateFloat3 = this._updateFloat3ForEffect;
  26181. this.updateFloat4 = this._updateFloat4ForEffect;
  26182. this.updateMatrix = this._updateMatrixForEffect;
  26183. this.updateVector3 = this._updateVector3ForEffect;
  26184. this.updateVector4 = this._updateVector4ForEffect;
  26185. this.updateColor3 = this._updateColor3ForEffect;
  26186. this.updateColor4 = this._updateColor4ForEffect;
  26187. }
  26188. else {
  26189. this._engine._uniformBuffers.push(this);
  26190. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26191. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26192. this.updateFloat = this._updateFloatForUniform;
  26193. this.updateFloat2 = this._updateFloat2ForUniform;
  26194. this.updateFloat3 = this._updateFloat3ForUniform;
  26195. this.updateFloat4 = this._updateFloat4ForUniform;
  26196. this.updateMatrix = this._updateMatrixForUniform;
  26197. this.updateVector3 = this._updateVector3ForUniform;
  26198. this.updateVector4 = this._updateVector4ForUniform;
  26199. this.updateColor3 = this._updateColor3ForUniform;
  26200. this.updateColor4 = this._updateColor4ForUniform;
  26201. }
  26202. }
  26203. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26204. // Properties
  26205. /**
  26206. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26207. * or just falling back on setUniformXXX calls.
  26208. */
  26209. get: function () {
  26210. return !this._noUBO;
  26211. },
  26212. enumerable: true,
  26213. configurable: true
  26214. });
  26215. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26216. /**
  26217. * Indicates if the WebGL underlying uniform buffer is in sync
  26218. * with the javascript cache data.
  26219. */
  26220. get: function () {
  26221. return !this._needSync;
  26222. },
  26223. enumerable: true,
  26224. configurable: true
  26225. });
  26226. /**
  26227. * Indicates if the WebGL underlying uniform buffer is dynamic.
  26228. * Also, a dynamic UniformBuffer will disable cache verification and always
  26229. * update the underlying WebGL uniform buffer to the GPU.
  26230. */
  26231. UniformBuffer.prototype.isDynamic = function () {
  26232. return this._dynamic;
  26233. };
  26234. /**
  26235. * The data cache on JS side.
  26236. */
  26237. UniformBuffer.prototype.getData = function () {
  26238. return this._bufferData;
  26239. };
  26240. /**
  26241. * The underlying WebGL Uniform buffer.
  26242. */
  26243. UniformBuffer.prototype.getBuffer = function () {
  26244. return this._buffer;
  26245. };
  26246. /**
  26247. * std140 layout specifies how to align data within an UBO structure.
  26248. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  26249. * for specs.
  26250. */
  26251. UniformBuffer.prototype._fillAlignment = function (size) {
  26252. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26253. // and 4x4 matrices
  26254. // TODO : change if other types are used
  26255. var alignment;
  26256. if (size <= 2) {
  26257. alignment = size;
  26258. }
  26259. else {
  26260. alignment = 4;
  26261. }
  26262. if ((this._uniformLocationPointer % alignment) !== 0) {
  26263. var oldPointer = this._uniformLocationPointer;
  26264. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26265. var diff = this._uniformLocationPointer - oldPointer;
  26266. for (var i = 0; i < diff; i++) {
  26267. this._data.push(0);
  26268. }
  26269. }
  26270. };
  26271. /**
  26272. * Adds an uniform in the buffer.
  26273. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26274. * for the layout to be correct !
  26275. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26276. * @param {number|number[]} size Data size, or data directly.
  26277. */
  26278. UniformBuffer.prototype.addUniform = function (name, size) {
  26279. if (this._noUBO) {
  26280. return;
  26281. }
  26282. if (this._uniformLocations[name] !== undefined) {
  26283. // Already existing uniform
  26284. return;
  26285. }
  26286. // This function must be called in the order of the shader layout !
  26287. // size can be the size of the uniform, or data directly
  26288. var data;
  26289. if (size instanceof Array) {
  26290. data = size;
  26291. size = data.length;
  26292. }
  26293. else {
  26294. size = size;
  26295. data = [];
  26296. // Fill with zeros
  26297. for (var i = 0; i < size; i++) {
  26298. data.push(0);
  26299. }
  26300. }
  26301. this._fillAlignment(size);
  26302. this._uniformSizes[name] = size;
  26303. this._uniformLocations[name] = this._uniformLocationPointer;
  26304. this._uniformLocationPointer += size;
  26305. for (var i = 0; i < size; i++) {
  26306. this._data.push(data[i]);
  26307. }
  26308. this._needSync = true;
  26309. };
  26310. /**
  26311. * Wrapper for addUniform.
  26312. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26313. * @param {Matrix} mat A 4x4 matrix.
  26314. */
  26315. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26316. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26317. };
  26318. /**
  26319. * Wrapper for addUniform.
  26320. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26321. * @param {number} x
  26322. * @param {number} y
  26323. */
  26324. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26325. var temp = [x, y];
  26326. this.addUniform(name, temp);
  26327. };
  26328. /**
  26329. * Wrapper for addUniform.
  26330. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26331. * @param {number} x
  26332. * @param {number} y
  26333. * @param {number} z
  26334. */
  26335. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26336. var temp = [x, y, z];
  26337. this.addUniform(name, temp);
  26338. };
  26339. /**
  26340. * Wrapper for addUniform.
  26341. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26342. * @param {Color3} color
  26343. */
  26344. UniformBuffer.prototype.addColor3 = function (name, color) {
  26345. var temp = [];
  26346. color.toArray(temp);
  26347. this.addUniform(name, temp);
  26348. };
  26349. /**
  26350. * Wrapper for addUniform.
  26351. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26352. * @param {Color3} color
  26353. * @param {number} alpha
  26354. */
  26355. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26356. var temp = [];
  26357. color.toArray(temp);
  26358. temp.push(alpha);
  26359. this.addUniform(name, temp);
  26360. };
  26361. /**
  26362. * Wrapper for addUniform.
  26363. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26364. * @param {Vector3} vector
  26365. */
  26366. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26367. var temp = [];
  26368. vector.toArray(temp);
  26369. this.addUniform(name, temp);
  26370. };
  26371. /**
  26372. * Wrapper for addUniform.
  26373. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26374. */
  26375. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26376. this.addUniform(name, 12);
  26377. };
  26378. /**
  26379. * Wrapper for addUniform.
  26380. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26381. */
  26382. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26383. this.addUniform(name, 8);
  26384. };
  26385. /**
  26386. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26387. */
  26388. UniformBuffer.prototype.create = function () {
  26389. if (this._noUBO) {
  26390. return;
  26391. }
  26392. if (this._buffer) {
  26393. return; // nothing to do
  26394. }
  26395. // See spec, alignment must be filled as a vec4
  26396. this._fillAlignment(4);
  26397. this._bufferData = new Float32Array(this._data);
  26398. this._rebuild();
  26399. this._needSync = true;
  26400. };
  26401. UniformBuffer.prototype._rebuild = function () {
  26402. if (this._noUBO) {
  26403. return;
  26404. }
  26405. if (this._dynamic) {
  26406. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26407. }
  26408. else {
  26409. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26410. }
  26411. };
  26412. /**
  26413. * Updates the WebGL Uniform Buffer on the GPU.
  26414. * If the `dynamic` flag is set to true, no cache comparison is done.
  26415. * Otherwise, the buffer will be updated only if the cache differs.
  26416. */
  26417. UniformBuffer.prototype.update = function () {
  26418. if (!this._buffer) {
  26419. this.create();
  26420. return;
  26421. }
  26422. if (!this._dynamic && !this._needSync) {
  26423. return;
  26424. }
  26425. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26426. this._needSync = false;
  26427. };
  26428. /**
  26429. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26430. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26431. * @param {number[]|Float32Array} data Flattened data
  26432. * @param {number} size Size of the data.
  26433. */
  26434. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26435. var location = this._uniformLocations[uniformName];
  26436. if (location === undefined) {
  26437. if (this._buffer) {
  26438. // Cannot add an uniform if the buffer is already created
  26439. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26440. return;
  26441. }
  26442. this.addUniform(uniformName, size);
  26443. location = this._uniformLocations[uniformName];
  26444. }
  26445. if (!this._buffer) {
  26446. this.create();
  26447. }
  26448. if (!this._dynamic) {
  26449. // Cache for static uniform buffers
  26450. var changed = false;
  26451. for (var i = 0; i < size; i++) {
  26452. if (this._bufferData[location + i] !== data[i]) {
  26453. changed = true;
  26454. this._bufferData[location + i] = data[i];
  26455. }
  26456. }
  26457. this._needSync = this._needSync || changed;
  26458. }
  26459. else {
  26460. // No cache for dynamic
  26461. for (var i = 0; i < size; i++) {
  26462. this._bufferData[location + i] = data[i];
  26463. }
  26464. }
  26465. };
  26466. // Update methods
  26467. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26468. // To match std140, matrix must be realigned
  26469. for (var i = 0; i < 3; i++) {
  26470. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26471. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26472. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26473. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26474. }
  26475. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26476. };
  26477. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26478. this._currentEffect.setMatrix3x3(name, matrix);
  26479. };
  26480. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26481. this._currentEffect.setMatrix2x2(name, matrix);
  26482. };
  26483. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26484. // To match std140, matrix must be realigned
  26485. for (var i = 0; i < 2; i++) {
  26486. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26487. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26488. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26489. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26490. }
  26491. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26492. };
  26493. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26494. this._currentEffect.setFloat(name, x);
  26495. };
  26496. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26497. UniformBuffer._tempBuffer[0] = x;
  26498. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26499. };
  26500. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26501. if (suffix === void 0) { suffix = ""; }
  26502. this._currentEffect.setFloat2(name + suffix, x, y);
  26503. };
  26504. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26505. if (suffix === void 0) { suffix = ""; }
  26506. UniformBuffer._tempBuffer[0] = x;
  26507. UniformBuffer._tempBuffer[1] = y;
  26508. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26509. };
  26510. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26511. if (suffix === void 0) { suffix = ""; }
  26512. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26513. };
  26514. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26515. if (suffix === void 0) { suffix = ""; }
  26516. UniformBuffer._tempBuffer[0] = x;
  26517. UniformBuffer._tempBuffer[1] = y;
  26518. UniformBuffer._tempBuffer[2] = z;
  26519. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26520. };
  26521. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26522. if (suffix === void 0) { suffix = ""; }
  26523. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26524. };
  26525. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26526. if (suffix === void 0) { suffix = ""; }
  26527. UniformBuffer._tempBuffer[0] = x;
  26528. UniformBuffer._tempBuffer[1] = y;
  26529. UniformBuffer._tempBuffer[2] = z;
  26530. UniformBuffer._tempBuffer[3] = w;
  26531. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26532. };
  26533. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26534. this._currentEffect.setMatrix(name, mat);
  26535. };
  26536. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26537. this.updateUniform(name, mat.toArray(), 16);
  26538. };
  26539. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26540. this._currentEffect.setVector3(name, vector);
  26541. };
  26542. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26543. vector.toArray(UniformBuffer._tempBuffer);
  26544. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26545. };
  26546. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26547. this._currentEffect.setVector4(name, vector);
  26548. };
  26549. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26550. vector.toArray(UniformBuffer._tempBuffer);
  26551. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26552. };
  26553. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26554. if (suffix === void 0) { suffix = ""; }
  26555. this._currentEffect.setColor3(name + suffix, color);
  26556. };
  26557. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26558. if (suffix === void 0) { suffix = ""; }
  26559. color.toArray(UniformBuffer._tempBuffer);
  26560. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26561. };
  26562. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26563. if (suffix === void 0) { suffix = ""; }
  26564. this._currentEffect.setColor4(name + suffix, color, alpha);
  26565. };
  26566. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26567. if (suffix === void 0) { suffix = ""; }
  26568. color.toArray(UniformBuffer._tempBuffer);
  26569. UniformBuffer._tempBuffer[3] = alpha;
  26570. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26571. };
  26572. /**
  26573. * Sets a sampler uniform on the effect.
  26574. * @param {string} name Name of the sampler.
  26575. * @param {Texture} texture
  26576. */
  26577. UniformBuffer.prototype.setTexture = function (name, texture) {
  26578. this._currentEffect.setTexture(name, texture);
  26579. };
  26580. /**
  26581. * Directly updates the value of the uniform in the cache AND on the GPU.
  26582. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26583. * @param {number[]|Float32Array} data Flattened data
  26584. */
  26585. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26586. this.updateUniform(uniformName, data, data.length);
  26587. this.update();
  26588. };
  26589. /**
  26590. * Binds this uniform buffer to an effect.
  26591. * @param {Effect} effect
  26592. * @param {string} name Name of the uniform block in the shader.
  26593. */
  26594. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26595. this._currentEffect = effect;
  26596. if (this._noUBO) {
  26597. return;
  26598. }
  26599. effect.bindUniformBuffer(this._buffer, name);
  26600. };
  26601. /**
  26602. * Disposes the uniform buffer.
  26603. */
  26604. UniformBuffer.prototype.dispose = function () {
  26605. if (this._noUBO) {
  26606. return;
  26607. }
  26608. var index = this._engine._uniformBuffers.indexOf(this);
  26609. if (index !== -1) {
  26610. this._engine._uniformBuffers.splice(index, 1);
  26611. }
  26612. if (!this._buffer) {
  26613. return;
  26614. }
  26615. if (this._engine._releaseBuffer(this._buffer)) {
  26616. this._buffer = null;
  26617. }
  26618. };
  26619. // Pool for avoiding memory leaks
  26620. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26621. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26622. return UniformBuffer;
  26623. }());
  26624. BABYLON.UniformBuffer = UniformBuffer;
  26625. })(BABYLON || (BABYLON = {}));
  26626. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26627. var BABYLON;
  26628. (function (BABYLON) {
  26629. var PushMaterial = (function (_super) {
  26630. __extends(PushMaterial, _super);
  26631. function PushMaterial(name, scene) {
  26632. var _this = _super.call(this, name, scene) || this;
  26633. _this.storeEffectOnSubMeshes = true;
  26634. return _this;
  26635. }
  26636. PushMaterial.prototype.getEffect = function () {
  26637. return this._activeEffect;
  26638. };
  26639. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26640. if (!mesh) {
  26641. return false;
  26642. }
  26643. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26644. return true;
  26645. }
  26646. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26647. };
  26648. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26649. this._activeEffect.setMatrix("world", world);
  26650. };
  26651. PushMaterial.prototype.bind = function (world, mesh) {
  26652. if (!mesh) {
  26653. return;
  26654. }
  26655. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26656. };
  26657. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26658. _super.prototype._afterBind.call(this, mesh);
  26659. this.getScene()._cachedEffect = effect;
  26660. };
  26661. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26662. if (visibility === void 0) { visibility = 1; }
  26663. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26664. };
  26665. return PushMaterial;
  26666. }(BABYLON.Material));
  26667. BABYLON.PushMaterial = PushMaterial;
  26668. })(BABYLON || (BABYLON = {}));
  26669. //# sourceMappingURL=babylon.pushMaterial.js.map
  26670. var BABYLON;
  26671. (function (BABYLON) {
  26672. var VertexData = (function () {
  26673. function VertexData() {
  26674. }
  26675. VertexData.prototype.set = function (data, kind) {
  26676. switch (kind) {
  26677. case BABYLON.VertexBuffer.PositionKind:
  26678. this.positions = data;
  26679. break;
  26680. case BABYLON.VertexBuffer.NormalKind:
  26681. this.normals = data;
  26682. break;
  26683. case BABYLON.VertexBuffer.TangentKind:
  26684. this.tangents = data;
  26685. break;
  26686. case BABYLON.VertexBuffer.UVKind:
  26687. this.uvs = data;
  26688. break;
  26689. case BABYLON.VertexBuffer.UV2Kind:
  26690. this.uvs2 = data;
  26691. break;
  26692. case BABYLON.VertexBuffer.UV3Kind:
  26693. this.uvs3 = data;
  26694. break;
  26695. case BABYLON.VertexBuffer.UV4Kind:
  26696. this.uvs4 = data;
  26697. break;
  26698. case BABYLON.VertexBuffer.UV5Kind:
  26699. this.uvs5 = data;
  26700. break;
  26701. case BABYLON.VertexBuffer.UV6Kind:
  26702. this.uvs6 = data;
  26703. break;
  26704. case BABYLON.VertexBuffer.ColorKind:
  26705. this.colors = data;
  26706. break;
  26707. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26708. this.matricesIndices = data;
  26709. break;
  26710. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26711. this.matricesWeights = data;
  26712. break;
  26713. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26714. this.matricesIndicesExtra = data;
  26715. break;
  26716. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26717. this.matricesWeightsExtra = data;
  26718. break;
  26719. }
  26720. };
  26721. /**
  26722. * Associates the vertexData to the passed Mesh.
  26723. * Sets it as updatable or not (default `false`).
  26724. * Returns the VertexData.
  26725. */
  26726. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26727. this._applyTo(mesh, updatable);
  26728. return this;
  26729. };
  26730. /**
  26731. * Associates the vertexData to the passed Geometry.
  26732. * Sets it as updatable or not (default `false`).
  26733. * Returns the VertexData.
  26734. */
  26735. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26736. this._applyTo(geometry, updatable);
  26737. return this;
  26738. };
  26739. /**
  26740. * Updates the associated mesh.
  26741. * Returns the VertexData.
  26742. */
  26743. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26744. this._update(mesh);
  26745. return this;
  26746. };
  26747. /**
  26748. * Updates the associated geometry.
  26749. * Returns the VertexData.
  26750. */
  26751. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26752. this._update(geometry);
  26753. return this;
  26754. };
  26755. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26756. if (this.positions) {
  26757. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26758. }
  26759. if (this.normals) {
  26760. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26761. }
  26762. if (this.tangents) {
  26763. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26764. }
  26765. if (this.uvs) {
  26766. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26767. }
  26768. if (this.uvs2) {
  26769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26770. }
  26771. if (this.uvs3) {
  26772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26773. }
  26774. if (this.uvs4) {
  26775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26776. }
  26777. if (this.uvs5) {
  26778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26779. }
  26780. if (this.uvs6) {
  26781. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26782. }
  26783. if (this.colors) {
  26784. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26785. }
  26786. if (this.matricesIndices) {
  26787. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26788. }
  26789. if (this.matricesWeights) {
  26790. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26791. }
  26792. if (this.matricesIndicesExtra) {
  26793. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26794. }
  26795. if (this.matricesWeightsExtra) {
  26796. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26797. }
  26798. if (this.indices) {
  26799. meshOrGeometry.setIndices(this.indices);
  26800. }
  26801. return this;
  26802. };
  26803. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26804. if (this.positions) {
  26805. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26806. }
  26807. if (this.normals) {
  26808. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26809. }
  26810. if (this.tangents) {
  26811. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26812. }
  26813. if (this.uvs) {
  26814. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26815. }
  26816. if (this.uvs2) {
  26817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26818. }
  26819. if (this.uvs3) {
  26820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26821. }
  26822. if (this.uvs4) {
  26823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26824. }
  26825. if (this.uvs5) {
  26826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26827. }
  26828. if (this.uvs6) {
  26829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26830. }
  26831. if (this.colors) {
  26832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26833. }
  26834. if (this.matricesIndices) {
  26835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26836. }
  26837. if (this.matricesWeights) {
  26838. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26839. }
  26840. if (this.matricesIndicesExtra) {
  26841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26842. }
  26843. if (this.matricesWeightsExtra) {
  26844. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26845. }
  26846. if (this.indices) {
  26847. meshOrGeometry.setIndices(this.indices);
  26848. }
  26849. return this;
  26850. };
  26851. /**
  26852. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26853. * Returns the VertexData.
  26854. */
  26855. VertexData.prototype.transform = function (matrix) {
  26856. var transformed = BABYLON.Vector3.Zero();
  26857. var index;
  26858. if (this.positions) {
  26859. var position = BABYLON.Vector3.Zero();
  26860. for (index = 0; index < this.positions.length; index += 3) {
  26861. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26862. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26863. this.positions[index] = transformed.x;
  26864. this.positions[index + 1] = transformed.y;
  26865. this.positions[index + 2] = transformed.z;
  26866. }
  26867. }
  26868. if (this.normals) {
  26869. var normal = BABYLON.Vector3.Zero();
  26870. for (index = 0; index < this.normals.length; index += 3) {
  26871. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26872. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26873. this.normals[index] = transformed.x;
  26874. this.normals[index + 1] = transformed.y;
  26875. this.normals[index + 2] = transformed.z;
  26876. }
  26877. }
  26878. if (this.tangents) {
  26879. var tangent = BABYLON.Vector4.Zero();
  26880. var tangentTransformed = BABYLON.Vector4.Zero();
  26881. for (index = 0; index < this.tangents.length; index += 4) {
  26882. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26883. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26884. this.tangents[index] = tangentTransformed.x;
  26885. this.tangents[index + 1] = tangentTransformed.y;
  26886. this.tangents[index + 2] = tangentTransformed.z;
  26887. this.tangents[index + 3] = tangentTransformed.w;
  26888. }
  26889. }
  26890. return this;
  26891. };
  26892. /**
  26893. * Merges the passed VertexData into the current one.
  26894. * Returns the modified VertexData.
  26895. */
  26896. VertexData.prototype.merge = function (other) {
  26897. if (other.indices) {
  26898. if (!this.indices) {
  26899. this.indices = [];
  26900. }
  26901. var offset = this.positions ? this.positions.length / 3 : 0;
  26902. for (var index = 0; index < other.indices.length; index++) {
  26903. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26904. this.indices.push(other.indices[index] + offset);
  26905. }
  26906. }
  26907. this.positions = this._mergeElement(this.positions, other.positions);
  26908. this.normals = this._mergeElement(this.normals, other.normals);
  26909. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26910. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26911. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26912. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26913. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26914. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26915. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26916. this.colors = this._mergeElement(this.colors, other.colors);
  26917. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26918. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26919. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26920. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26921. return this;
  26922. };
  26923. VertexData.prototype._mergeElement = function (source, other) {
  26924. if (!other)
  26925. return source;
  26926. if (!source)
  26927. return other;
  26928. var len = other.length + source.length;
  26929. var isSrcTypedArray = source instanceof Float32Array;
  26930. var isOthTypedArray = other instanceof Float32Array;
  26931. // use non-loop method when the source is Float32Array
  26932. if (isSrcTypedArray) {
  26933. var ret32 = new Float32Array(len);
  26934. ret32.set(source);
  26935. ret32.set(other, source.length);
  26936. return ret32;
  26937. // source is number[], when other is also use concat
  26938. }
  26939. else if (!isOthTypedArray) {
  26940. return source.concat(other);
  26941. // source is a number[], but other is a Float32Array, loop required
  26942. }
  26943. else {
  26944. var ret = source.slice(0); // copy source to a separate array
  26945. for (var i = 0, len = other.length; i < len; i++) {
  26946. ret.push(other[i]);
  26947. }
  26948. return ret;
  26949. }
  26950. };
  26951. /**
  26952. * Serializes the VertexData.
  26953. * Returns a serialized object.
  26954. */
  26955. VertexData.prototype.serialize = function () {
  26956. var serializationObject = this.serialize();
  26957. if (this.positions) {
  26958. serializationObject.positions = this.positions;
  26959. }
  26960. if (this.normals) {
  26961. serializationObject.normals = this.normals;
  26962. }
  26963. if (this.tangents) {
  26964. serializationObject.tangents = this.tangents;
  26965. }
  26966. if (this.uvs) {
  26967. serializationObject.uvs = this.uvs;
  26968. }
  26969. if (this.uvs2) {
  26970. serializationObject.uvs2 = this.uvs2;
  26971. }
  26972. if (this.uvs3) {
  26973. serializationObject.uvs3 = this.uvs3;
  26974. }
  26975. if (this.uvs4) {
  26976. serializationObject.uvs4 = this.uvs4;
  26977. }
  26978. if (this.uvs5) {
  26979. serializationObject.uvs5 = this.uvs5;
  26980. }
  26981. if (this.uvs6) {
  26982. serializationObject.uvs6 = this.uvs6;
  26983. }
  26984. if (this.colors) {
  26985. serializationObject.colors = this.colors;
  26986. }
  26987. if (this.matricesIndices) {
  26988. serializationObject.matricesIndices = this.matricesIndices;
  26989. serializationObject.matricesIndices._isExpanded = true;
  26990. }
  26991. if (this.matricesWeights) {
  26992. serializationObject.matricesWeights = this.matricesWeights;
  26993. }
  26994. if (this.matricesIndicesExtra) {
  26995. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26996. serializationObject.matricesIndicesExtra._isExpanded = true;
  26997. }
  26998. if (this.matricesWeightsExtra) {
  26999. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27000. }
  27001. serializationObject.indices = this.indices;
  27002. return serializationObject;
  27003. };
  27004. // Statics
  27005. /**
  27006. * Returns the object VertexData associated to the passed mesh.
  27007. */
  27008. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  27009. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  27010. };
  27011. /**
  27012. * Returns the object VertexData associated to the passed geometry.
  27013. */
  27014. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  27015. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  27016. };
  27017. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  27018. var result = new VertexData();
  27019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27020. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  27021. }
  27022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27023. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  27024. }
  27025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27026. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  27027. }
  27028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27029. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  27030. }
  27031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27032. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  27033. }
  27034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27035. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  27036. }
  27037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27038. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  27039. }
  27040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27041. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  27042. }
  27043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27044. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  27045. }
  27046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27047. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  27048. }
  27049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27050. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  27051. }
  27052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27053. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  27054. }
  27055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27056. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  27057. }
  27058. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27059. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  27060. }
  27061. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27062. return result;
  27063. };
  27064. /**
  27065. * Creates the vertexData of the Ribbon.
  27066. */
  27067. VertexData.CreateRibbon = function (options) {
  27068. var pathArray = options.pathArray;
  27069. var closeArray = options.closeArray || false;
  27070. var closePath = options.closePath || false;
  27071. var invertUV = options.invertUV || false;
  27072. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27073. var offset = options.offset || defaultOffset;
  27074. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27075. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27076. var customUV = options.uvs;
  27077. var customColors = options.colors;
  27078. var positions = [];
  27079. var indices = [];
  27080. var normals = [];
  27081. var uvs = [];
  27082. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27083. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27084. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27085. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27086. var minlg; // minimal length among all paths from pathArray
  27087. var lg = []; // array of path lengths : nb of vertex per path
  27088. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27089. var p; // path iterator
  27090. var i; // point iterator
  27091. var j; // point iterator
  27092. // if single path in pathArray
  27093. if (pathArray.length < 2) {
  27094. var ar1 = [];
  27095. var ar2 = [];
  27096. for (i = 0; i < pathArray[0].length - offset; i++) {
  27097. ar1.push(pathArray[0][i]);
  27098. ar2.push(pathArray[0][i + offset]);
  27099. }
  27100. pathArray = [ar1, ar2];
  27101. }
  27102. // positions and horizontal distances (u)
  27103. var idc = 0;
  27104. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  27105. var path;
  27106. var l;
  27107. minlg = pathArray[0].length;
  27108. var vectlg;
  27109. var dist;
  27110. for (p = 0; p < pathArray.length; p++) {
  27111. uTotalDistance[p] = 0;
  27112. us[p] = [0];
  27113. path = pathArray[p];
  27114. l = path.length;
  27115. minlg = (minlg < l) ? minlg : l;
  27116. j = 0;
  27117. while (j < l) {
  27118. positions.push(path[j].x, path[j].y, path[j].z);
  27119. if (j > 0) {
  27120. vectlg = path[j].subtract(path[j - 1]).length();
  27121. dist = vectlg + uTotalDistance[p];
  27122. us[p].push(dist);
  27123. uTotalDistance[p] = dist;
  27124. }
  27125. j++;
  27126. }
  27127. if (closePath) {
  27128. j--;
  27129. positions.push(path[0].x, path[0].y, path[0].z);
  27130. vectlg = path[j].subtract(path[0]).length();
  27131. dist = vectlg + uTotalDistance[p];
  27132. us[p].push(dist);
  27133. uTotalDistance[p] = dist;
  27134. }
  27135. lg[p] = l + closePathCorr;
  27136. idx[p] = idc;
  27137. idc += (l + closePathCorr);
  27138. }
  27139. // vertical distances (v)
  27140. var path1;
  27141. var path2;
  27142. var vertex1;
  27143. var vertex2;
  27144. for (i = 0; i < minlg + closePathCorr; i++) {
  27145. vTotalDistance[i] = 0;
  27146. vs[i] = [0];
  27147. for (p = 0; p < pathArray.length - 1; p++) {
  27148. path1 = pathArray[p];
  27149. path2 = pathArray[p + 1];
  27150. if (i === minlg) {
  27151. vertex1 = path1[0];
  27152. vertex2 = path2[0];
  27153. }
  27154. else {
  27155. vertex1 = path1[i];
  27156. vertex2 = path2[i];
  27157. }
  27158. vectlg = vertex2.subtract(vertex1).length();
  27159. dist = vectlg + vTotalDistance[i];
  27160. vs[i].push(dist);
  27161. vTotalDistance[i] = dist;
  27162. }
  27163. if (closeArray) {
  27164. path1 = pathArray[p];
  27165. path2 = pathArray[0];
  27166. if (i === minlg) {
  27167. vertex2 = path2[0];
  27168. }
  27169. vectlg = vertex2.subtract(vertex1).length();
  27170. dist = vectlg + vTotalDistance[i];
  27171. vTotalDistance[i] = dist;
  27172. }
  27173. }
  27174. // uvs
  27175. var u;
  27176. var v;
  27177. if (customUV) {
  27178. for (p = 0; p < customUV.length; p++) {
  27179. uvs.push(customUV[p].x, customUV[p].y);
  27180. }
  27181. }
  27182. else {
  27183. for (p = 0; p < pathArray.length; p++) {
  27184. for (i = 0; i < minlg + closePathCorr; i++) {
  27185. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27186. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27187. if (invertUV) {
  27188. uvs.push(v, u);
  27189. }
  27190. else {
  27191. uvs.push(u, v);
  27192. }
  27193. }
  27194. }
  27195. }
  27196. // indices
  27197. p = 0; // path index
  27198. var pi = 0; // positions array index
  27199. var l1 = lg[p] - 1; // path1 length
  27200. var l2 = lg[p + 1] - 1; // path2 length
  27201. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27202. var shft = idx[1] - idx[0]; // shift
  27203. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27204. while (pi <= min && p < path1nb) {
  27205. // 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
  27206. indices.push(pi, pi + shft, pi + 1);
  27207. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27208. pi += 1;
  27209. if (pi === min) {
  27210. p++;
  27211. if (p === lg.length - 1) {
  27212. shft = idx[0] - idx[p];
  27213. l1 = lg[p] - 1;
  27214. l2 = lg[0] - 1;
  27215. }
  27216. else {
  27217. shft = idx[p + 1] - idx[p];
  27218. l1 = lg[p] - 1;
  27219. l2 = lg[p + 1] - 1;
  27220. }
  27221. pi = idx[p];
  27222. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27223. }
  27224. }
  27225. // normals
  27226. VertexData.ComputeNormals(positions, indices, normals);
  27227. if (closePath) {
  27228. var indexFirst = 0;
  27229. var indexLast = 0;
  27230. for (p = 0; p < pathArray.length; p++) {
  27231. indexFirst = idx[p] * 3;
  27232. if (p + 1 < pathArray.length) {
  27233. indexLast = (idx[p + 1] - 1) * 3;
  27234. }
  27235. else {
  27236. indexLast = normals.length - 3;
  27237. }
  27238. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27239. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27240. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27241. normals[indexLast] = normals[indexFirst];
  27242. normals[indexLast + 1] = normals[indexFirst + 1];
  27243. normals[indexLast + 2] = normals[indexFirst + 2];
  27244. }
  27245. }
  27246. // sides
  27247. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27248. // Colors
  27249. if (customColors) {
  27250. var colors = new Float32Array(customColors.length * 4);
  27251. for (var c = 0; c < customColors.length; c++) {
  27252. colors[c * 4] = customColors[c].r;
  27253. colors[c * 4 + 1] = customColors[c].g;
  27254. colors[c * 4 + 2] = customColors[c].b;
  27255. colors[c * 4 + 3] = customColors[c].a;
  27256. }
  27257. }
  27258. // Result
  27259. var vertexData = new VertexData();
  27260. var positions32 = new Float32Array(positions);
  27261. var normals32 = new Float32Array(normals);
  27262. var uvs32 = new Float32Array(uvs);
  27263. vertexData.indices = indices;
  27264. vertexData.positions = positions32;
  27265. vertexData.normals = normals32;
  27266. vertexData.uvs = uvs32;
  27267. if (customColors) {
  27268. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27269. }
  27270. if (closePath) {
  27271. vertexData._idx = idx;
  27272. }
  27273. return vertexData;
  27274. };
  27275. /**
  27276. * Creates the VertexData of the Box.
  27277. */
  27278. VertexData.CreateBox = function (options) {
  27279. var normalsSource = [
  27280. new BABYLON.Vector3(0, 0, 1),
  27281. new BABYLON.Vector3(0, 0, -1),
  27282. new BABYLON.Vector3(1, 0, 0),
  27283. new BABYLON.Vector3(-1, 0, 0),
  27284. new BABYLON.Vector3(0, 1, 0),
  27285. new BABYLON.Vector3(0, -1, 0)
  27286. ];
  27287. var indices = [];
  27288. var positions = [];
  27289. var normals = [];
  27290. var uvs = [];
  27291. var width = options.width || options.size || 1;
  27292. var height = options.height || options.size || 1;
  27293. var depth = options.depth || options.size || 1;
  27294. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27295. var faceUV = options.faceUV || new Array(6);
  27296. var faceColors = options.faceColors;
  27297. var colors = [];
  27298. // default face colors and UV if undefined
  27299. for (var f = 0; f < 6; f++) {
  27300. if (faceUV[f] === undefined) {
  27301. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27302. }
  27303. if (faceColors && faceColors[f] === undefined) {
  27304. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27305. }
  27306. }
  27307. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27308. // Create each face in turn.
  27309. for (var index = 0; index < normalsSource.length; index++) {
  27310. var normal = normalsSource[index];
  27311. // Get two vectors perpendicular to the face normal and to each other.
  27312. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27313. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27314. // Six indices (two triangles) per face.
  27315. var verticesLength = positions.length / 3;
  27316. indices.push(verticesLength);
  27317. indices.push(verticesLength + 1);
  27318. indices.push(verticesLength + 2);
  27319. indices.push(verticesLength);
  27320. indices.push(verticesLength + 2);
  27321. indices.push(verticesLength + 3);
  27322. // Four vertices per face.
  27323. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27324. positions.push(vertex.x, vertex.y, vertex.z);
  27325. normals.push(normal.x, normal.y, normal.z);
  27326. uvs.push(faceUV[index].z, faceUV[index].w);
  27327. if (faceColors) {
  27328. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27329. }
  27330. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27331. positions.push(vertex.x, vertex.y, vertex.z);
  27332. normals.push(normal.x, normal.y, normal.z);
  27333. uvs.push(faceUV[index].x, faceUV[index].w);
  27334. if (faceColors) {
  27335. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27336. }
  27337. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27338. positions.push(vertex.x, vertex.y, vertex.z);
  27339. normals.push(normal.x, normal.y, normal.z);
  27340. uvs.push(faceUV[index].x, faceUV[index].y);
  27341. if (faceColors) {
  27342. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27343. }
  27344. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27345. positions.push(vertex.x, vertex.y, vertex.z);
  27346. normals.push(normal.x, normal.y, normal.z);
  27347. uvs.push(faceUV[index].z, faceUV[index].y);
  27348. if (faceColors) {
  27349. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27350. }
  27351. }
  27352. // sides
  27353. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27354. // Result
  27355. var vertexData = new VertexData();
  27356. vertexData.indices = indices;
  27357. vertexData.positions = positions;
  27358. vertexData.normals = normals;
  27359. vertexData.uvs = uvs;
  27360. if (faceColors) {
  27361. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27362. vertexData.colors = totalColors;
  27363. }
  27364. return vertexData;
  27365. };
  27366. /**
  27367. * Creates the VertexData of the Sphere.
  27368. */
  27369. VertexData.CreateSphere = function (options) {
  27370. var segments = options.segments || 32;
  27371. var diameterX = options.diameterX || options.diameter || 1;
  27372. var diameterY = options.diameterY || options.diameter || 1;
  27373. var diameterZ = options.diameterZ || options.diameter || 1;
  27374. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27375. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27376. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27377. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27378. var totalZRotationSteps = 2 + segments;
  27379. var totalYRotationSteps = 2 * totalZRotationSteps;
  27380. var indices = [];
  27381. var positions = [];
  27382. var normals = [];
  27383. var uvs = [];
  27384. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27385. var normalizedZ = zRotationStep / totalZRotationSteps;
  27386. var angleZ = normalizedZ * Math.PI * slice;
  27387. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27388. var normalizedY = yRotationStep / totalYRotationSteps;
  27389. var angleY = normalizedY * Math.PI * 2 * arc;
  27390. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27391. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27392. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27393. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27394. var vertex = complete.multiply(radius);
  27395. var normal = complete.divide(radius).normalize();
  27396. positions.push(vertex.x, vertex.y, vertex.z);
  27397. normals.push(normal.x, normal.y, normal.z);
  27398. uvs.push(normalizedY, normalizedZ);
  27399. }
  27400. if (zRotationStep > 0) {
  27401. var verticesCount = positions.length / 3;
  27402. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27403. indices.push((firstIndex));
  27404. indices.push((firstIndex + 1));
  27405. indices.push(firstIndex + totalYRotationSteps + 1);
  27406. indices.push((firstIndex + totalYRotationSteps + 1));
  27407. indices.push((firstIndex + 1));
  27408. indices.push((firstIndex + totalYRotationSteps + 2));
  27409. }
  27410. }
  27411. }
  27412. // Sides
  27413. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27414. // Result
  27415. var vertexData = new VertexData();
  27416. vertexData.indices = indices;
  27417. vertexData.positions = positions;
  27418. vertexData.normals = normals;
  27419. vertexData.uvs = uvs;
  27420. return vertexData;
  27421. };
  27422. /**
  27423. * Creates the VertexData of the Cylinder or Cone.
  27424. */
  27425. VertexData.CreateCylinder = function (options) {
  27426. var height = options.height || 2;
  27427. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27428. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27429. var tessellation = options.tessellation || 24;
  27430. var subdivisions = options.subdivisions || 1;
  27431. var hasRings = options.hasRings;
  27432. var enclose = options.enclose;
  27433. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27434. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27435. var faceUV = options.faceUV || new Array(3);
  27436. var faceColors = options.faceColors;
  27437. // default face colors and UV if undefined
  27438. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27439. var ringNb = (hasRings) ? subdivisions : 1;
  27440. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27441. var f;
  27442. for (f = 0; f < surfaceNb; f++) {
  27443. if (faceColors && faceColors[f] === undefined) {
  27444. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27445. }
  27446. }
  27447. for (f = 0; f < surfaceNb; f++) {
  27448. if (faceUV && faceUV[f] === undefined) {
  27449. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27450. }
  27451. }
  27452. var indices = [];
  27453. var positions = [];
  27454. var normals = [];
  27455. var uvs = [];
  27456. var colors = [];
  27457. var angle_step = Math.PI * 2 * arc / tessellation;
  27458. var angle;
  27459. var h;
  27460. var radius;
  27461. var tan = (diameterBottom - diameterTop) / 2 / height;
  27462. var ringVertex = BABYLON.Vector3.Zero();
  27463. var ringNormal = BABYLON.Vector3.Zero();
  27464. var ringFirstVertex = BABYLON.Vector3.Zero();
  27465. var ringFirstNormal = BABYLON.Vector3.Zero();
  27466. var quadNormal = BABYLON.Vector3.Zero();
  27467. var Y = BABYLON.Axis.Y;
  27468. // positions, normals, uvs
  27469. var i;
  27470. var j;
  27471. var r;
  27472. var ringIdx = 1;
  27473. var s = 1; // surface index
  27474. var cs = 0;
  27475. var v = 0;
  27476. for (i = 0; i <= subdivisions; i++) {
  27477. h = i / subdivisions;
  27478. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27479. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27480. for (r = 0; r < ringIdx; r++) {
  27481. if (hasRings) {
  27482. s += r;
  27483. }
  27484. if (enclose) {
  27485. s += 2 * r;
  27486. }
  27487. for (j = 0; j <= tessellation; j++) {
  27488. angle = j * angle_step;
  27489. // position
  27490. ringVertex.x = Math.cos(-angle) * radius;
  27491. ringVertex.y = -height / 2 + h * height;
  27492. ringVertex.z = Math.sin(-angle) * radius;
  27493. // normal
  27494. if (diameterTop === 0 && i === subdivisions) {
  27495. // if no top cap, reuse former normals
  27496. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27497. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27498. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27499. }
  27500. else {
  27501. ringNormal.x = ringVertex.x;
  27502. ringNormal.z = ringVertex.z;
  27503. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27504. ringNormal.normalize();
  27505. }
  27506. // keep first ring vertex values for enclose
  27507. if (j === 0) {
  27508. ringFirstVertex.copyFrom(ringVertex);
  27509. ringFirstNormal.copyFrom(ringNormal);
  27510. }
  27511. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27512. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27513. if (hasRings) {
  27514. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27515. }
  27516. else {
  27517. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27518. }
  27519. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27520. if (faceColors) {
  27521. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27522. }
  27523. }
  27524. // if enclose, add four vertices and their dedicated normals
  27525. if (arc !== 1 && enclose) {
  27526. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27527. positions.push(0, ringVertex.y, 0);
  27528. positions.push(0, ringVertex.y, 0);
  27529. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27530. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27531. quadNormal.normalize();
  27532. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27533. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27534. quadNormal.normalize();
  27535. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27536. if (hasRings) {
  27537. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27538. }
  27539. else {
  27540. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27541. }
  27542. uvs.push(faceUV[s + 1].x, v);
  27543. uvs.push(faceUV[s + 1].z, v);
  27544. if (hasRings) {
  27545. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27546. }
  27547. else {
  27548. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27549. }
  27550. uvs.push(faceUV[s + 2].x, v);
  27551. uvs.push(faceUV[s + 2].z, v);
  27552. if (faceColors) {
  27553. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27554. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27555. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27556. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27557. }
  27558. }
  27559. if (cs !== s) {
  27560. cs = s;
  27561. }
  27562. }
  27563. }
  27564. // indices
  27565. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27566. var s;
  27567. i = 0;
  27568. for (s = 0; s < subdivisions; s++) {
  27569. for (j = 0; j < tessellation; j++) {
  27570. var i0 = i * (e + 1) + j;
  27571. var i1 = (i + 1) * (e + 1) + j;
  27572. var i2 = i * (e + 1) + (j + 1);
  27573. var i3 = (i + 1) * (e + 1) + (j + 1);
  27574. indices.push(i0, i1, i2);
  27575. indices.push(i3, i2, i1);
  27576. }
  27577. if (arc !== 1 && enclose) {
  27578. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27579. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27580. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27581. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27582. }
  27583. i = (hasRings) ? (i + 2) : (i + 1);
  27584. }
  27585. // Caps
  27586. var createCylinderCap = function (isTop) {
  27587. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27588. if (radius === 0) {
  27589. return;
  27590. }
  27591. // Cap positions, normals & uvs
  27592. var angle;
  27593. var circleVector;
  27594. var i;
  27595. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27596. var c;
  27597. if (faceColors) {
  27598. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27599. }
  27600. // cap center
  27601. var vbase = positions.length / 3;
  27602. var offset = isTop ? height / 2 : -height / 2;
  27603. var center = new BABYLON.Vector3(0, offset, 0);
  27604. positions.push(center.x, center.y, center.z);
  27605. normals.push(0, isTop ? 1 : -1, 0);
  27606. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27607. if (faceColors) {
  27608. colors.push(c.r, c.g, c.b, c.a);
  27609. }
  27610. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27611. for (i = 0; i <= tessellation; i++) {
  27612. angle = Math.PI * 2 * i * arc / tessellation;
  27613. var cos = Math.cos(-angle);
  27614. var sin = Math.sin(-angle);
  27615. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27616. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27617. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27618. normals.push(0, isTop ? 1 : -1, 0);
  27619. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27620. if (faceColors) {
  27621. colors.push(c.r, c.g, c.b, c.a);
  27622. }
  27623. }
  27624. // Cap indices
  27625. for (i = 0; i < tessellation; i++) {
  27626. if (!isTop) {
  27627. indices.push(vbase);
  27628. indices.push(vbase + (i + 1));
  27629. indices.push(vbase + (i + 2));
  27630. }
  27631. else {
  27632. indices.push(vbase);
  27633. indices.push(vbase + (i + 2));
  27634. indices.push(vbase + (i + 1));
  27635. }
  27636. }
  27637. };
  27638. // add caps to geometry
  27639. createCylinderCap(false);
  27640. createCylinderCap(true);
  27641. // Sides
  27642. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27643. var vertexData = new VertexData();
  27644. vertexData.indices = indices;
  27645. vertexData.positions = positions;
  27646. vertexData.normals = normals;
  27647. vertexData.uvs = uvs;
  27648. if (faceColors) {
  27649. vertexData.colors = colors;
  27650. }
  27651. return vertexData;
  27652. };
  27653. /**
  27654. * Creates the VertexData of the Torus.
  27655. */
  27656. VertexData.CreateTorus = function (options) {
  27657. var indices = [];
  27658. var positions = [];
  27659. var normals = [];
  27660. var uvs = [];
  27661. var diameter = options.diameter || 1;
  27662. var thickness = options.thickness || 0.5;
  27663. var tessellation = options.tessellation || 16;
  27664. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27665. var stride = tessellation + 1;
  27666. for (var i = 0; i <= tessellation; i++) {
  27667. var u = i / tessellation;
  27668. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27669. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27670. for (var j = 0; j <= tessellation; j++) {
  27671. var v = 1 - j / tessellation;
  27672. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27673. var dx = Math.cos(innerAngle);
  27674. var dy = Math.sin(innerAngle);
  27675. // Create a vertex.
  27676. var normal = new BABYLON.Vector3(dx, dy, 0);
  27677. var position = normal.scale(thickness / 2);
  27678. var textureCoordinate = new BABYLON.Vector2(u, v);
  27679. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27680. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27681. positions.push(position.x, position.y, position.z);
  27682. normals.push(normal.x, normal.y, normal.z);
  27683. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27684. // And create indices for two triangles.
  27685. var nextI = (i + 1) % stride;
  27686. var nextJ = (j + 1) % stride;
  27687. indices.push(i * stride + j);
  27688. indices.push(i * stride + nextJ);
  27689. indices.push(nextI * stride + j);
  27690. indices.push(i * stride + nextJ);
  27691. indices.push(nextI * stride + nextJ);
  27692. indices.push(nextI * stride + j);
  27693. }
  27694. }
  27695. // Sides
  27696. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27697. // Result
  27698. var vertexData = new VertexData();
  27699. vertexData.indices = indices;
  27700. vertexData.positions = positions;
  27701. vertexData.normals = normals;
  27702. vertexData.uvs = uvs;
  27703. return vertexData;
  27704. };
  27705. /**
  27706. * Creates the VertexData of the LineSystem.
  27707. */
  27708. VertexData.CreateLineSystem = function (options) {
  27709. var indices = [];
  27710. var positions = [];
  27711. var lines = options.lines;
  27712. var idx = 0;
  27713. for (var l = 0; l < lines.length; l++) {
  27714. var points = lines[l];
  27715. for (var index = 0; index < points.length; index++) {
  27716. positions.push(points[index].x, points[index].y, points[index].z);
  27717. if (index > 0) {
  27718. indices.push(idx - 1);
  27719. indices.push(idx);
  27720. }
  27721. idx++;
  27722. }
  27723. }
  27724. var vertexData = new VertexData();
  27725. vertexData.indices = indices;
  27726. vertexData.positions = positions;
  27727. return vertexData;
  27728. };
  27729. /**
  27730. * Create the VertexData of the DashedLines.
  27731. */
  27732. VertexData.CreateDashedLines = function (options) {
  27733. var dashSize = options.dashSize || 3;
  27734. var gapSize = options.gapSize || 1;
  27735. var dashNb = options.dashNb || 200;
  27736. var points = options.points;
  27737. var positions = new Array();
  27738. var indices = new Array();
  27739. var curvect = BABYLON.Vector3.Zero();
  27740. var lg = 0;
  27741. var nb = 0;
  27742. var shft = 0;
  27743. var dashshft = 0;
  27744. var curshft = 0;
  27745. var idx = 0;
  27746. var i = 0;
  27747. for (i = 0; i < points.length - 1; i++) {
  27748. points[i + 1].subtractToRef(points[i], curvect);
  27749. lg += curvect.length();
  27750. }
  27751. shft = lg / dashNb;
  27752. dashshft = dashSize * shft / (dashSize + gapSize);
  27753. for (i = 0; i < points.length - 1; i++) {
  27754. points[i + 1].subtractToRef(points[i], curvect);
  27755. nb = Math.floor(curvect.length() / shft);
  27756. curvect.normalize();
  27757. for (var j = 0; j < nb; j++) {
  27758. curshft = shft * j;
  27759. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27760. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27761. indices.push(idx, idx + 1);
  27762. idx += 2;
  27763. }
  27764. }
  27765. // Result
  27766. var vertexData = new VertexData();
  27767. vertexData.positions = positions;
  27768. vertexData.indices = indices;
  27769. return vertexData;
  27770. };
  27771. /**
  27772. * Creates the VertexData of the Ground.
  27773. */
  27774. VertexData.CreateGround = function (options) {
  27775. var indices = [];
  27776. var positions = [];
  27777. var normals = [];
  27778. var uvs = [];
  27779. var row, col;
  27780. var width = options.width || 1;
  27781. var height = options.height || 1;
  27782. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27783. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27784. for (row = 0; row <= subdivisionsY; row++) {
  27785. for (col = 0; col <= subdivisionsX; col++) {
  27786. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27787. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27788. positions.push(position.x, position.y, position.z);
  27789. normals.push(normal.x, normal.y, normal.z);
  27790. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27791. }
  27792. }
  27793. for (row = 0; row < subdivisionsY; row++) {
  27794. for (col = 0; col < subdivisionsX; col++) {
  27795. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27796. indices.push(col + 1 + row * (subdivisionsX + 1));
  27797. indices.push(col + row * (subdivisionsX + 1));
  27798. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27799. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27800. indices.push(col + row * (subdivisionsX + 1));
  27801. }
  27802. }
  27803. // Result
  27804. var vertexData = new VertexData();
  27805. vertexData.indices = indices;
  27806. vertexData.positions = positions;
  27807. vertexData.normals = normals;
  27808. vertexData.uvs = uvs;
  27809. return vertexData;
  27810. };
  27811. /**
  27812. * Creates the VertexData of the TiledGround.
  27813. */
  27814. VertexData.CreateTiledGround = function (options) {
  27815. var xmin = options.xmin || -1.0;
  27816. var zmin = options.zmin || -1.0;
  27817. var xmax = options.xmax || 1.0;
  27818. var zmax = options.zmax || 1.0;
  27819. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27820. var precision = options.precision || { w: 1, h: 1 };
  27821. var indices = [];
  27822. var positions = [];
  27823. var normals = [];
  27824. var uvs = [];
  27825. var row, col, tileRow, tileCol;
  27826. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27827. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27828. precision.w = (precision.w < 1) ? 1 : precision.w;
  27829. precision.h = (precision.h < 1) ? 1 : precision.h;
  27830. var tileSize = {
  27831. 'w': (xmax - xmin) / subdivisions.w,
  27832. 'h': (zmax - zmin) / subdivisions.h
  27833. };
  27834. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27835. // Indices
  27836. var base = positions.length / 3;
  27837. var rowLength = precision.w + 1;
  27838. for (row = 0; row < precision.h; row++) {
  27839. for (col = 0; col < precision.w; col++) {
  27840. var square = [
  27841. base + col + row * rowLength,
  27842. base + (col + 1) + row * rowLength,
  27843. base + (col + 1) + (row + 1) * rowLength,
  27844. base + col + (row + 1) * rowLength
  27845. ];
  27846. indices.push(square[1]);
  27847. indices.push(square[2]);
  27848. indices.push(square[3]);
  27849. indices.push(square[0]);
  27850. indices.push(square[1]);
  27851. indices.push(square[3]);
  27852. }
  27853. }
  27854. // Position, normals and uvs
  27855. var position = BABYLON.Vector3.Zero();
  27856. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27857. for (row = 0; row <= precision.h; row++) {
  27858. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27859. for (col = 0; col <= precision.w; col++) {
  27860. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27861. position.y = 0;
  27862. positions.push(position.x, position.y, position.z);
  27863. normals.push(normal.x, normal.y, normal.z);
  27864. uvs.push(col / precision.w, row / precision.h);
  27865. }
  27866. }
  27867. }
  27868. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27869. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27870. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27871. }
  27872. }
  27873. // Result
  27874. var vertexData = new VertexData();
  27875. vertexData.indices = indices;
  27876. vertexData.positions = positions;
  27877. vertexData.normals = normals;
  27878. vertexData.uvs = uvs;
  27879. return vertexData;
  27880. };
  27881. /**
  27882. * Creates the VertexData of the Ground designed from a heightmap.
  27883. */
  27884. VertexData.CreateGroundFromHeightMap = function (options) {
  27885. var indices = [];
  27886. var positions = [];
  27887. var normals = [];
  27888. var uvs = [];
  27889. var row, col;
  27890. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27891. // Vertices
  27892. for (row = 0; row <= options.subdivisions; row++) {
  27893. for (col = 0; col <= options.subdivisions; col++) {
  27894. 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));
  27895. // Compute height
  27896. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27897. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27898. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27899. var r = options.buffer[pos] / 255.0;
  27900. var g = options.buffer[pos + 1] / 255.0;
  27901. var b = options.buffer[pos + 2] / 255.0;
  27902. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27903. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27904. // Add vertex
  27905. positions.push(position.x, position.y, position.z);
  27906. normals.push(0, 0, 0);
  27907. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27908. }
  27909. }
  27910. // Indices
  27911. for (row = 0; row < options.subdivisions; row++) {
  27912. for (col = 0; col < options.subdivisions; col++) {
  27913. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27914. indices.push(col + 1 + row * (options.subdivisions + 1));
  27915. indices.push(col + row * (options.subdivisions + 1));
  27916. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27917. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27918. indices.push(col + row * (options.subdivisions + 1));
  27919. }
  27920. }
  27921. // Normals
  27922. VertexData.ComputeNormals(positions, indices, normals);
  27923. // Result
  27924. var vertexData = new VertexData();
  27925. vertexData.indices = indices;
  27926. vertexData.positions = positions;
  27927. vertexData.normals = normals;
  27928. vertexData.uvs = uvs;
  27929. return vertexData;
  27930. };
  27931. /**
  27932. * Creates the VertexData of the Plane.
  27933. */
  27934. VertexData.CreatePlane = function (options) {
  27935. var indices = [];
  27936. var positions = [];
  27937. var normals = [];
  27938. var uvs = [];
  27939. var width = options.width || options.size || 1;
  27940. var height = options.height || options.size || 1;
  27941. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27942. // Vertices
  27943. var halfWidth = width / 2.0;
  27944. var halfHeight = height / 2.0;
  27945. positions.push(-halfWidth, -halfHeight, 0);
  27946. normals.push(0, 0, -1.0);
  27947. uvs.push(0.0, 0.0);
  27948. positions.push(halfWidth, -halfHeight, 0);
  27949. normals.push(0, 0, -1.0);
  27950. uvs.push(1.0, 0.0);
  27951. positions.push(halfWidth, halfHeight, 0);
  27952. normals.push(0, 0, -1.0);
  27953. uvs.push(1.0, 1.0);
  27954. positions.push(-halfWidth, halfHeight, 0);
  27955. normals.push(0, 0, -1.0);
  27956. uvs.push(0.0, 1.0);
  27957. // Indices
  27958. indices.push(0);
  27959. indices.push(1);
  27960. indices.push(2);
  27961. indices.push(0);
  27962. indices.push(2);
  27963. indices.push(3);
  27964. // Sides
  27965. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27966. // Result
  27967. var vertexData = new VertexData();
  27968. vertexData.indices = indices;
  27969. vertexData.positions = positions;
  27970. vertexData.normals = normals;
  27971. vertexData.uvs = uvs;
  27972. return vertexData;
  27973. };
  27974. /**
  27975. * Creates the VertexData of the Disc or regular Polygon.
  27976. */
  27977. VertexData.CreateDisc = function (options) {
  27978. var positions = [];
  27979. var indices = [];
  27980. var normals = [];
  27981. var uvs = [];
  27982. var radius = options.radius || 0.5;
  27983. var tessellation = options.tessellation || 64;
  27984. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27985. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27986. // positions and uvs
  27987. positions.push(0, 0, 0); // disc center first
  27988. uvs.push(0.5, 0.5);
  27989. var theta = Math.PI * 2 * arc;
  27990. var step = theta / tessellation;
  27991. for (var a = 0; a < theta; a += step) {
  27992. var x = Math.cos(a);
  27993. var y = Math.sin(a);
  27994. var u = (x + 1) / 2;
  27995. var v = (1 - y) / 2;
  27996. positions.push(radius * x, radius * y, 0);
  27997. uvs.push(u, v);
  27998. }
  27999. if (arc === 1) {
  28000. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28001. uvs.push(uvs[2], uvs[3]);
  28002. }
  28003. //indices
  28004. var vertexNb = positions.length / 3;
  28005. for (var i = 1; i < vertexNb - 1; i++) {
  28006. indices.push(i + 1, 0, i);
  28007. }
  28008. // result
  28009. VertexData.ComputeNormals(positions, indices, normals);
  28010. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28011. var vertexData = new VertexData();
  28012. vertexData.indices = indices;
  28013. vertexData.positions = positions;
  28014. vertexData.normals = normals;
  28015. vertexData.uvs = uvs;
  28016. return vertexData;
  28017. };
  28018. /**
  28019. * Re-creates the VertexData of the Polygon for sideOrientation.
  28020. */
  28021. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  28022. var faceUV = fUV || new Array(3);
  28023. var faceColors = fColors;
  28024. var colors = [];
  28025. // default face colors and UV if undefined
  28026. for (var f = 0; f < 3; f++) {
  28027. if (faceUV[f] === undefined) {
  28028. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28029. }
  28030. if (faceColors && faceColors[f] === undefined) {
  28031. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28032. }
  28033. }
  28034. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28035. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28036. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28037. var indices = polygon.getIndices();
  28038. // set face colours and textures
  28039. var idx = 0;
  28040. var face = 0;
  28041. for (var index = 0; index < normals.length; index += 3) {
  28042. //Edge Face no. 1
  28043. if (Math.abs(normals[index + 1]) < 0.001) {
  28044. face = 1;
  28045. }
  28046. //Top Face no. 0
  28047. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  28048. face = 0;
  28049. }
  28050. //Bottom Face no. 2
  28051. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  28052. face = 2;
  28053. }
  28054. idx = index / 3;
  28055. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  28056. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  28057. if (faceColors) {
  28058. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  28059. }
  28060. }
  28061. // sides
  28062. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  28063. // Result
  28064. var vertexData = new VertexData();
  28065. vertexData.indices = indices;
  28066. vertexData.positions = positions;
  28067. vertexData.normals = normals;
  28068. vertexData.uvs = uvs;
  28069. if (faceColors) {
  28070. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28071. vertexData.colors = totalColors;
  28072. }
  28073. return vertexData;
  28074. };
  28075. /**
  28076. * Creates the VertexData of the IcoSphere.
  28077. */
  28078. VertexData.CreateIcoSphere = function (options) {
  28079. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28080. var radius = options.radius || 1;
  28081. var flat = (options.flat === undefined) ? true : options.flat;
  28082. var subdivisions = options.subdivisions || 4;
  28083. var radiusX = options.radiusX || radius;
  28084. var radiusY = options.radiusY || radius;
  28085. var radiusZ = options.radiusZ || radius;
  28086. var t = (1 + Math.sqrt(5)) / 2;
  28087. // 12 vertex x,y,z
  28088. var ico_vertices = [
  28089. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28090. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28091. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28092. ];
  28093. // index of 3 vertex makes a face of icopshere
  28094. var ico_indices = [
  28095. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28096. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28097. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28098. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28099. ];
  28100. // vertex for uv have aliased position, not for UV
  28101. var vertices_unalias_id = [
  28102. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28103. // vertex alias
  28104. 0,
  28105. 2,
  28106. 3,
  28107. 3,
  28108. 3,
  28109. 4,
  28110. 7,
  28111. 8,
  28112. 9,
  28113. 9,
  28114. 10,
  28115. 11 // 23: B + 12
  28116. ];
  28117. // uv as integer step (not pixels !)
  28118. var ico_vertexuv = [
  28119. 5, 1, 3, 1, 6, 4, 0, 0,
  28120. 5, 3, 4, 2, 2, 2, 4, 0,
  28121. 2, 0, 1, 1, 6, 0, 6, 2,
  28122. // vertex alias (for same vertex on different faces)
  28123. 0, 4,
  28124. 3, 3,
  28125. 4, 4,
  28126. 3, 1,
  28127. 4, 2,
  28128. 4, 4,
  28129. 0, 2,
  28130. 1, 1,
  28131. 2, 2,
  28132. 3, 3,
  28133. 1, 3,
  28134. 2, 4 // 23: B + 12
  28135. ];
  28136. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28137. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28138. // First island of uv mapping
  28139. // v = 4h 3+ 2
  28140. // v = 3h 9+ 4
  28141. // v = 2h 9+ 5 B
  28142. // v = 1h 9 1 0
  28143. // v = 0h 3 8 7 A
  28144. // u = 0 1 2 3 4 5 6 *a
  28145. // Second island of uv mapping
  28146. // v = 4h 0+ B+ 4+
  28147. // v = 3h A+ 2+
  28148. // v = 2h 7+ 6 3+
  28149. // v = 1h 8+ 3+
  28150. // v = 0h
  28151. // u = 0 1 2 3 4 5 6 *a
  28152. // Face layout on texture UV mapping
  28153. // ============
  28154. // \ 4 /\ 16 / ======
  28155. // \ / \ / /\ 11 /
  28156. // \/ 7 \/ / \ /
  28157. // ======= / 10 \/
  28158. // /\ 17 /\ =======
  28159. // / \ / \ \ 15 /\
  28160. // / 8 \/ 12 \ \ / \
  28161. // ============ \/ 6 \
  28162. // \ 18 /\ ============
  28163. // \ / \ \ 5 /\ 0 /
  28164. // \/ 13 \ \ / \ /
  28165. // ======= \/ 1 \/
  28166. // =============
  28167. // /\ 19 /\ 2 /\
  28168. // / \ / \ / \
  28169. // / 14 \/ 9 \/ 3 \
  28170. // ===================
  28171. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28172. var ustep = 138 / 1024;
  28173. var vstep = 239 / 1024;
  28174. var uoffset = 60 / 1024;
  28175. var voffset = 26 / 1024;
  28176. // Second island should have margin, not to touch the first island
  28177. // avoid any borderline artefact in pixel rounding
  28178. var island_u_offset = -40 / 1024;
  28179. var island_v_offset = +20 / 1024;
  28180. // face is either island 0 or 1 :
  28181. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28182. var island = [
  28183. 0, 0, 0, 0, 1,
  28184. 0, 0, 1, 1, 0,
  28185. 0, 0, 1, 1, 0,
  28186. 0, 1, 1, 1, 0 // 15 - 19
  28187. ];
  28188. var indices = [];
  28189. var positions = [];
  28190. var normals = [];
  28191. var uvs = [];
  28192. var current_indice = 0;
  28193. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28194. var face_vertex_pos = new Array(3);
  28195. var face_vertex_uv = new Array(3);
  28196. var v012;
  28197. for (v012 = 0; v012 < 3; v012++) {
  28198. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28199. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28200. }
  28201. // create all with normals
  28202. for (var face = 0; face < 20; face++) {
  28203. // 3 vertex per face
  28204. for (v012 = 0; v012 < 3; v012++) {
  28205. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28206. var v_id = ico_indices[3 * face + v012];
  28207. // vertex have 3D position (x,y,z)
  28208. 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]);
  28209. // Normalize to get normal, then scale to radius
  28210. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28211. // uv Coordinates from vertex ID
  28212. 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);
  28213. }
  28214. // Subdivide the face (interpolate pos, norm, uv)
  28215. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28216. // - norm is linear interpolation of vertex corner normal
  28217. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28218. // - uv is linear interpolation
  28219. //
  28220. // Topology is as below for sub-divide by 2
  28221. // vertex shown as v0,v1,v2
  28222. // interp index is i1 to progress in range [v0,v1[
  28223. // interp index is i2 to progress in range [v0,v2[
  28224. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28225. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28226. //
  28227. //
  28228. // i2 v2
  28229. // ^ ^
  28230. // / / \
  28231. // / / \
  28232. // / / \
  28233. // / / (0,1) \
  28234. // / #---------\
  28235. // / / \ (0,0)'/ \
  28236. // / / \ / \
  28237. // / / \ / \
  28238. // / / (0,0) \ / (1,0) \
  28239. // / #---------#---------\
  28240. // v0 v1
  28241. //
  28242. // --------------------> i1
  28243. //
  28244. // interp of (i1,i2):
  28245. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28246. // along i1 : lerp(x0,x1, i1/(S-i2))
  28247. //
  28248. // centroid of triangle is needed to get help normal computation
  28249. // (c1,c2) are used for centroid location
  28250. var interp_vertex = function (i1, i2, c1, c2) {
  28251. // vertex is interpolated from
  28252. // - face_vertex_pos[0..2]
  28253. // - face_vertex_uv[0..2]
  28254. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28255. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28256. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28257. pos_interp.normalize();
  28258. var vertex_normal;
  28259. if (flat) {
  28260. // in flat mode, recalculate normal as face centroid normal
  28261. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28262. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28263. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28264. }
  28265. else {
  28266. // in smooth mode, recalculate normal from each single vertex position
  28267. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28268. }
  28269. // Vertex normal need correction due to X,Y,Z radius scaling
  28270. vertex_normal.x /= radiusX;
  28271. vertex_normal.y /= radiusY;
  28272. vertex_normal.z /= radiusZ;
  28273. vertex_normal.normalize();
  28274. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28275. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28276. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28277. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28278. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28279. uvs.push(uv_interp.x, uv_interp.y);
  28280. // push each vertex has member of a face
  28281. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28282. indices.push(current_indice);
  28283. current_indice++;
  28284. };
  28285. for (var i2 = 0; i2 < subdivisions; i2++) {
  28286. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28287. // face : (i1,i2) for /\ :
  28288. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28289. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28290. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28291. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28292. if (i1 + i2 + 1 < subdivisions) {
  28293. // face : (i1,i2)' for \/ :
  28294. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28295. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28296. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28297. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28298. }
  28299. }
  28300. }
  28301. }
  28302. // Sides
  28303. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28304. // Result
  28305. var vertexData = new VertexData();
  28306. vertexData.indices = indices;
  28307. vertexData.positions = positions;
  28308. vertexData.normals = normals;
  28309. vertexData.uvs = uvs;
  28310. return vertexData;
  28311. };
  28312. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28313. /**
  28314. * Creates the VertexData of the Polyhedron.
  28315. */
  28316. VertexData.CreatePolyhedron = function (options) {
  28317. // provided polyhedron types :
  28318. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28319. // 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)
  28320. var polyhedra = [];
  28321. 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]] };
  28322. 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]] };
  28323. polyhedra[2] = {
  28324. 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]],
  28325. 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]]
  28326. };
  28327. polyhedra[3] = {
  28328. 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]],
  28329. 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]]
  28330. };
  28331. polyhedra[4] = {
  28332. 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]],
  28333. 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]]
  28334. };
  28335. 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]] };
  28336. 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]] };
  28337. 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]] };
  28338. 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]] };
  28339. 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]] };
  28340. 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]] };
  28341. 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]] };
  28342. 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]] };
  28343. 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]] };
  28344. polyhedra[14] = {
  28345. 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]],
  28346. 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]]
  28347. };
  28348. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28349. var size = options.size;
  28350. var sizeX = options.sizeX || size || 1;
  28351. var sizeY = options.sizeY || size || 1;
  28352. var sizeZ = options.sizeZ || size || 1;
  28353. var data = options.custom || polyhedra[type];
  28354. var nbfaces = data.face.length;
  28355. var faceUV = options.faceUV || new Array(nbfaces);
  28356. var faceColors = options.faceColors;
  28357. var flat = (options.flat === undefined) ? true : options.flat;
  28358. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28359. var positions = [];
  28360. var indices = [];
  28361. var normals = [];
  28362. var uvs = [];
  28363. var colors = [];
  28364. var index = 0;
  28365. var faceIdx = 0; // face cursor in the array "indexes"
  28366. var indexes = [];
  28367. var i = 0;
  28368. var f = 0;
  28369. var u, v, ang, x, y, tmp;
  28370. // default face colors and UV if undefined
  28371. if (flat) {
  28372. for (f = 0; f < nbfaces; f++) {
  28373. if (faceColors && faceColors[f] === undefined) {
  28374. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28375. }
  28376. if (faceUV && faceUV[f] === undefined) {
  28377. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28378. }
  28379. }
  28380. }
  28381. if (!flat) {
  28382. for (i = 0; i < data.vertex.length; i++) {
  28383. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28384. uvs.push(0, 0);
  28385. }
  28386. for (f = 0; f < nbfaces; f++) {
  28387. for (i = 0; i < data.face[f].length - 2; i++) {
  28388. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28389. }
  28390. }
  28391. }
  28392. else {
  28393. for (f = 0; f < nbfaces; f++) {
  28394. var fl = data.face[f].length; // number of vertices of the current face
  28395. ang = 2 * Math.PI / fl;
  28396. x = 0.5 * Math.tan(ang / 2);
  28397. y = 0.5;
  28398. // positions, uvs, colors
  28399. for (i = 0; i < fl; i++) {
  28400. // positions
  28401. 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);
  28402. indexes.push(index);
  28403. index++;
  28404. // uvs
  28405. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28406. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28407. uvs.push(u, v);
  28408. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28409. y = x * Math.sin(ang) + y * Math.cos(ang);
  28410. x = tmp;
  28411. // colors
  28412. if (faceColors) {
  28413. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28414. }
  28415. }
  28416. // indices from indexes
  28417. for (i = 0; i < fl - 2; i++) {
  28418. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28419. }
  28420. faceIdx += fl;
  28421. }
  28422. }
  28423. VertexData.ComputeNormals(positions, indices, normals);
  28424. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28425. var vertexData = new VertexData();
  28426. vertexData.positions = positions;
  28427. vertexData.indices = indices;
  28428. vertexData.normals = normals;
  28429. vertexData.uvs = uvs;
  28430. if (faceColors && flat) {
  28431. vertexData.colors = colors;
  28432. }
  28433. return vertexData;
  28434. };
  28435. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28436. /**
  28437. * Creates the VertexData of the Torus Knot.
  28438. */
  28439. VertexData.CreateTorusKnot = function (options) {
  28440. var indices = [];
  28441. var positions = [];
  28442. var normals = [];
  28443. var uvs = [];
  28444. var radius = options.radius || 2;
  28445. var tube = options.tube || 0.5;
  28446. var radialSegments = options.radialSegments || 32;
  28447. var tubularSegments = options.tubularSegments || 32;
  28448. var p = options.p || 2;
  28449. var q = options.q || 3;
  28450. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28451. // Helper
  28452. var getPos = function (angle) {
  28453. var cu = Math.cos(angle);
  28454. var su = Math.sin(angle);
  28455. var quOverP = q / p * angle;
  28456. var cs = Math.cos(quOverP);
  28457. var tx = radius * (2 + cs) * 0.5 * cu;
  28458. var ty = radius * (2 + cs) * su * 0.5;
  28459. var tz = radius * Math.sin(quOverP) * 0.5;
  28460. return new BABYLON.Vector3(tx, ty, tz);
  28461. };
  28462. // Vertices
  28463. var i;
  28464. var j;
  28465. for (i = 0; i <= radialSegments; i++) {
  28466. var modI = i % radialSegments;
  28467. var u = modI / radialSegments * 2 * p * Math.PI;
  28468. var p1 = getPos(u);
  28469. var p2 = getPos(u + 0.01);
  28470. var tang = p2.subtract(p1);
  28471. var n = p2.add(p1);
  28472. var bitan = BABYLON.Vector3.Cross(tang, n);
  28473. n = BABYLON.Vector3.Cross(bitan, tang);
  28474. bitan.normalize();
  28475. n.normalize();
  28476. for (j = 0; j < tubularSegments; j++) {
  28477. var modJ = j % tubularSegments;
  28478. var v = modJ / tubularSegments * 2 * Math.PI;
  28479. var cx = -tube * Math.cos(v);
  28480. var cy = tube * Math.sin(v);
  28481. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28482. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28483. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28484. uvs.push(i / radialSegments);
  28485. uvs.push(j / tubularSegments);
  28486. }
  28487. }
  28488. for (i = 0; i < radialSegments; i++) {
  28489. for (j = 0; j < tubularSegments; j++) {
  28490. var jNext = (j + 1) % tubularSegments;
  28491. var a = i * tubularSegments + j;
  28492. var b = (i + 1) * tubularSegments + j;
  28493. var c = (i + 1) * tubularSegments + jNext;
  28494. var d = i * tubularSegments + jNext;
  28495. indices.push(d);
  28496. indices.push(b);
  28497. indices.push(a);
  28498. indices.push(d);
  28499. indices.push(c);
  28500. indices.push(b);
  28501. }
  28502. }
  28503. // Normals
  28504. VertexData.ComputeNormals(positions, indices, normals);
  28505. // Sides
  28506. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28507. // Result
  28508. var vertexData = new VertexData();
  28509. vertexData.indices = indices;
  28510. vertexData.positions = positions;
  28511. vertexData.normals = normals;
  28512. vertexData.uvs = uvs;
  28513. return vertexData;
  28514. };
  28515. // Tools
  28516. /**
  28517. * @param {any} - positions (number[] or Float32Array)
  28518. * @param {any} - indices (number[] or Uint16Array)
  28519. * @param {any} - normals (number[] or Float32Array)
  28520. * options (optional) :
  28521. * facetPositions : optional array of facet positions (vector3)
  28522. * facetNormals : optional array of facet normals (vector3)
  28523. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28524. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28525. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28526. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28527. * bInfo : optional bounding info, required for facetPartitioning computation
  28528. */
  28529. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28530. // temporary scalar variables
  28531. var index = 0; // facet index
  28532. var p1p2x = 0.0; // p1p2 vector x coordinate
  28533. var p1p2y = 0.0; // p1p2 vector y coordinate
  28534. var p1p2z = 0.0; // p1p2 vector z coordinate
  28535. var p3p2x = 0.0; // p3p2 vector x coordinate
  28536. var p3p2y = 0.0; // p3p2 vector y coordinate
  28537. var p3p2z = 0.0; // p3p2 vector z coordinate
  28538. var faceNormalx = 0.0; // facet normal x coordinate
  28539. var faceNormaly = 0.0; // facet normal y coordinate
  28540. var faceNormalz = 0.0; // facet normal z coordinate
  28541. var length = 0.0; // facet normal length before normalization
  28542. var v1x = 0; // vector1 x index in the positions array
  28543. var v1y = 0; // vector1 y index in the positions array
  28544. var v1z = 0; // vector1 z index in the positions array
  28545. var v2x = 0; // vector2 x index in the positions array
  28546. var v2y = 0; // vector2 y index in the positions array
  28547. var v2z = 0; // vector2 z index in the positions array
  28548. var v3x = 0; // vector3 x index in the positions array
  28549. var v3y = 0; // vector3 y index in the positions array
  28550. var v3z = 0; // vector3 z index in the positions array
  28551. var computeFacetNormals = false;
  28552. var computeFacetPositions = false;
  28553. var computeFacetPartitioning = false;
  28554. var faceNormalSign = 1;
  28555. if (options) {
  28556. computeFacetNormals = (options.facetNormals) ? true : false;
  28557. computeFacetPositions = (options.facetPositions) ? true : false;
  28558. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28559. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28560. }
  28561. // facetPartitioning reinit if needed
  28562. if (computeFacetPartitioning) {
  28563. var ox = 0; // X partitioning index for facet position
  28564. var oy = 0; // Y partinioning index for facet position
  28565. var oz = 0; // Z partinioning index for facet position
  28566. var b1x = 0; // X partitioning index for facet v1 vertex
  28567. var b1y = 0; // Y partitioning index for facet v1 vertex
  28568. var b1z = 0; // z partitioning index for facet v1 vertex
  28569. var b2x = 0; // X partitioning index for facet v2 vertex
  28570. var b2y = 0; // Y partitioning index for facet v2 vertex
  28571. var b2z = 0; // Z partitioning index for facet v2 vertex
  28572. var b3x = 0; // X partitioning index for facet v3 vertex
  28573. var b3y = 0; // Y partitioning index for facet v3 vertex
  28574. var b3z = 0; // Z partitioning index for facet v3 vertex
  28575. var block_idx_o = 0; // facet barycenter block index
  28576. var block_idx_v1 = 0; // v1 vertex block index
  28577. var block_idx_v2 = 0; // v2 vertex block index
  28578. var block_idx_v3 = 0; // v3 vertex block index
  28579. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28580. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28581. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28582. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28583. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28584. var subSq = options.subDiv.max * options.subDiv.max;
  28585. options.facetPartitioning.length = 0;
  28586. }
  28587. // reset the normals
  28588. for (index = 0; index < positions.length; index++) {
  28589. normals[index] = 0.0;
  28590. }
  28591. // Loop : 1 indice triplet = 1 facet
  28592. var nbFaces = indices.length / 3;
  28593. for (index = 0; index < nbFaces; index++) {
  28594. // get the indexes of the coordinates of each vertex of the facet
  28595. v1x = indices[index * 3] * 3;
  28596. v1y = v1x + 1;
  28597. v1z = v1x + 2;
  28598. v2x = indices[index * 3 + 1] * 3;
  28599. v2y = v2x + 1;
  28600. v2z = v2x + 2;
  28601. v3x = indices[index * 3 + 2] * 3;
  28602. v3y = v3x + 1;
  28603. v3z = v3x + 2;
  28604. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28605. p1p2y = positions[v1y] - positions[v2y];
  28606. p1p2z = positions[v1z] - positions[v2z];
  28607. p3p2x = positions[v3x] - positions[v2x];
  28608. p3p2y = positions[v3y] - positions[v2y];
  28609. p3p2z = positions[v3z] - positions[v2z];
  28610. // compute the face normal with the cross product
  28611. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28612. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28613. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28614. // normalize this normal and store it in the array facetData
  28615. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28616. length = (length === 0) ? 1.0 : length;
  28617. faceNormalx /= length;
  28618. faceNormaly /= length;
  28619. faceNormalz /= length;
  28620. if (computeFacetNormals) {
  28621. options.facetNormals[index].x = faceNormalx;
  28622. options.facetNormals[index].y = faceNormaly;
  28623. options.facetNormals[index].z = faceNormalz;
  28624. }
  28625. if (computeFacetPositions) {
  28626. // compute and the facet barycenter coordinates in the array facetPositions
  28627. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28628. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28629. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28630. }
  28631. if (computeFacetPartitioning) {
  28632. // store the facet indexes in arrays in the main facetPartitioning array :
  28633. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28634. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28635. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28636. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28637. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28638. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28639. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28640. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28641. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28642. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28643. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28644. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28645. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28646. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28647. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28648. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28649. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28650. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28651. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28652. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28653. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28654. // push each facet index in each block containing the vertex
  28655. options.facetPartitioning[block_idx_v1].push(index);
  28656. if (block_idx_v2 != block_idx_v1) {
  28657. options.facetPartitioning[block_idx_v2].push(index);
  28658. }
  28659. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28660. options.facetPartitioning[block_idx_v3].push(index);
  28661. }
  28662. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28663. options.facetPartitioning[block_idx_o].push(index);
  28664. }
  28665. }
  28666. // compute the normals anyway
  28667. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28668. normals[v1y] += faceNormaly;
  28669. normals[v1z] += faceNormalz;
  28670. normals[v2x] += faceNormalx;
  28671. normals[v2y] += faceNormaly;
  28672. normals[v2z] += faceNormalz;
  28673. normals[v3x] += faceNormalx;
  28674. normals[v3y] += faceNormaly;
  28675. normals[v3z] += faceNormalz;
  28676. }
  28677. // last normalization of each normal
  28678. for (index = 0; index < normals.length / 3; index++) {
  28679. faceNormalx = normals[index * 3];
  28680. faceNormaly = normals[index * 3 + 1];
  28681. faceNormalz = normals[index * 3 + 2];
  28682. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28683. length = (length === 0) ? 1.0 : length;
  28684. faceNormalx /= length;
  28685. faceNormaly /= length;
  28686. faceNormalz /= length;
  28687. normals[index * 3] = faceNormalx;
  28688. normals[index * 3 + 1] = faceNormaly;
  28689. normals[index * 3 + 2] = faceNormalz;
  28690. }
  28691. };
  28692. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28693. var li = indices.length;
  28694. var ln = normals.length;
  28695. var i;
  28696. var n;
  28697. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28698. switch (sideOrientation) {
  28699. case BABYLON.Mesh.FRONTSIDE:
  28700. // nothing changed
  28701. break;
  28702. case BABYLON.Mesh.BACKSIDE:
  28703. var tmp;
  28704. // indices
  28705. for (i = 0; i < li; i += 3) {
  28706. tmp = indices[i];
  28707. indices[i] = indices[i + 2];
  28708. indices[i + 2] = tmp;
  28709. }
  28710. // normals
  28711. for (n = 0; n < ln; n++) {
  28712. normals[n] = -normals[n];
  28713. }
  28714. break;
  28715. case BABYLON.Mesh.DOUBLESIDE:
  28716. // positions
  28717. var lp = positions.length;
  28718. var l = lp / 3;
  28719. for (var p = 0; p < lp; p++) {
  28720. positions[lp + p] = positions[p];
  28721. }
  28722. // indices
  28723. for (i = 0; i < li; i += 3) {
  28724. indices[i + li] = indices[i + 2] + l;
  28725. indices[i + 1 + li] = indices[i + 1] + l;
  28726. indices[i + 2 + li] = indices[i] + l;
  28727. }
  28728. // normals
  28729. for (n = 0; n < ln; n++) {
  28730. normals[ln + n] = -normals[n];
  28731. }
  28732. // uvs
  28733. var lu = uvs.length;
  28734. var u = 0;
  28735. for (u = 0; u < lu; u++) {
  28736. uvs[u + lu] = uvs[u];
  28737. }
  28738. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28739. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28740. u = 0;
  28741. for (i = 0; i < lu / 2; i++) {
  28742. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28743. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28744. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28745. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28746. u += 2;
  28747. }
  28748. break;
  28749. }
  28750. };
  28751. /**
  28752. * Creates a new VertexData from the imported parameters.
  28753. */
  28754. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28755. var vertexData = new VertexData();
  28756. // positions
  28757. var positions = parsedVertexData.positions;
  28758. if (positions) {
  28759. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28760. }
  28761. // normals
  28762. var normals = parsedVertexData.normals;
  28763. if (normals) {
  28764. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28765. }
  28766. // tangents
  28767. var tangents = parsedVertexData.tangents;
  28768. if (tangents) {
  28769. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28770. }
  28771. // uvs
  28772. var uvs = parsedVertexData.uvs;
  28773. if (uvs) {
  28774. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28775. }
  28776. // uv2s
  28777. var uv2s = parsedVertexData.uv2s;
  28778. if (uv2s) {
  28779. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28780. }
  28781. // uv3s
  28782. var uv3s = parsedVertexData.uv3s;
  28783. if (uv3s) {
  28784. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28785. }
  28786. // uv4s
  28787. var uv4s = parsedVertexData.uv4s;
  28788. if (uv4s) {
  28789. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28790. }
  28791. // uv5s
  28792. var uv5s = parsedVertexData.uv5s;
  28793. if (uv5s) {
  28794. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28795. }
  28796. // uv6s
  28797. var uv6s = parsedVertexData.uv6s;
  28798. if (uv6s) {
  28799. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28800. }
  28801. // colors
  28802. var colors = parsedVertexData.colors;
  28803. if (colors) {
  28804. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28805. }
  28806. // matricesIndices
  28807. var matricesIndices = parsedVertexData.matricesIndices;
  28808. if (matricesIndices) {
  28809. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28810. }
  28811. // matricesWeights
  28812. var matricesWeights = parsedVertexData.matricesWeights;
  28813. if (matricesWeights) {
  28814. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28815. }
  28816. // indices
  28817. var indices = parsedVertexData.indices;
  28818. if (indices) {
  28819. vertexData.indices = indices;
  28820. }
  28821. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28822. };
  28823. return VertexData;
  28824. }());
  28825. BABYLON.VertexData = VertexData;
  28826. })(BABYLON || (BABYLON = {}));
  28827. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28828. var BABYLON;
  28829. (function (BABYLON) {
  28830. var Geometry = (function () {
  28831. function Geometry(id, scene, vertexData, updatable, mesh) {
  28832. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28833. this._totalVertices = 0;
  28834. this._isDisposed = false;
  28835. this.id = id;
  28836. this._engine = scene.getEngine();
  28837. this._meshes = [];
  28838. this._scene = scene;
  28839. //Init vertex buffer cache
  28840. this._vertexBuffers = {};
  28841. this._indices = [];
  28842. this._updatable = updatable;
  28843. // vertexData
  28844. if (vertexData) {
  28845. this.setAllVerticesData(vertexData, updatable);
  28846. }
  28847. else {
  28848. this._totalVertices = 0;
  28849. this._indices = [];
  28850. }
  28851. if (this._engine.getCaps().vertexArrayObject) {
  28852. this._vertexArrayObjects = {};
  28853. }
  28854. // applyToMesh
  28855. if (mesh) {
  28856. if (mesh.getClassName() === "LinesMesh") {
  28857. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28858. this.updateExtend();
  28859. }
  28860. this.applyToMesh(mesh);
  28861. mesh.computeWorldMatrix(true);
  28862. }
  28863. }
  28864. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28865. /**
  28866. * 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
  28867. * @returns The Bias Vector
  28868. */
  28869. get: function () {
  28870. return this._boundingBias;
  28871. },
  28872. set: function (value) {
  28873. if (this._boundingBias && this._boundingBias.equals(value)) {
  28874. return;
  28875. }
  28876. this._boundingBias = value.clone();
  28877. this.updateBoundingInfo(true, null);
  28878. },
  28879. enumerable: true,
  28880. configurable: true
  28881. });
  28882. Object.defineProperty(Geometry.prototype, "extend", {
  28883. get: function () {
  28884. return this._extend;
  28885. },
  28886. enumerable: true,
  28887. configurable: true
  28888. });
  28889. Geometry.prototype.getScene = function () {
  28890. return this._scene;
  28891. };
  28892. Geometry.prototype.getEngine = function () {
  28893. return this._engine;
  28894. };
  28895. Geometry.prototype.isReady = function () {
  28896. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28897. };
  28898. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28899. get: function () {
  28900. for (var index = 0; index < this._meshes.length; index++) {
  28901. if (!this._meshes[index].doNotSerialize) {
  28902. return false;
  28903. }
  28904. }
  28905. return true;
  28906. },
  28907. enumerable: true,
  28908. configurable: true
  28909. });
  28910. Geometry.prototype._rebuild = function () {
  28911. if (this._vertexArrayObjects) {
  28912. this._vertexArrayObjects = {};
  28913. }
  28914. // Index buffer
  28915. if (this._meshes.length !== 0 && this._indices) {
  28916. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28917. }
  28918. // Vertex buffers
  28919. for (var key in this._vertexBuffers) {
  28920. var vertexBuffer = this._vertexBuffers[key];
  28921. vertexBuffer._rebuild();
  28922. }
  28923. };
  28924. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28925. vertexData.applyToGeometry(this, updatable);
  28926. this.notifyUpdate();
  28927. };
  28928. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28929. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28930. this.setVerticesBuffer(buffer);
  28931. };
  28932. Geometry.prototype.removeVerticesData = function (kind) {
  28933. if (this._vertexBuffers[kind]) {
  28934. this._vertexBuffers[kind].dispose();
  28935. delete this._vertexBuffers[kind];
  28936. }
  28937. };
  28938. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28939. var kind = buffer.getKind();
  28940. if (this._vertexBuffers[kind]) {
  28941. this._vertexBuffers[kind].dispose();
  28942. }
  28943. this._vertexBuffers[kind] = buffer;
  28944. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28945. var data = buffer.getData();
  28946. var stride = buffer.getStrideSize();
  28947. this._totalVertices = data.length / stride;
  28948. this.updateExtend(data, stride);
  28949. this._resetPointsArrayCache();
  28950. var meshes = this._meshes;
  28951. var numOfMeshes = meshes.length;
  28952. for (var index = 0; index < numOfMeshes; index++) {
  28953. var mesh = meshes[index];
  28954. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28955. mesh._createGlobalSubMesh(false);
  28956. mesh.computeWorldMatrix(true);
  28957. }
  28958. }
  28959. this.notifyUpdate(kind);
  28960. if (this._vertexArrayObjects) {
  28961. this._disposeVertexArrayObjects();
  28962. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28963. }
  28964. };
  28965. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28966. var vertexBuffer = this.getVertexBuffer(kind);
  28967. if (!vertexBuffer) {
  28968. return;
  28969. }
  28970. vertexBuffer.updateDirectly(data, offset);
  28971. this.notifyUpdate(kind);
  28972. };
  28973. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28974. var vertexBuffer = this.getVertexBuffer(kind);
  28975. if (!vertexBuffer) {
  28976. return;
  28977. }
  28978. vertexBuffer.update(data);
  28979. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28980. var stride = vertexBuffer.getStrideSize();
  28981. this._totalVertices = data.length / stride;
  28982. this.updateBoundingInfo(updateExtends, data);
  28983. }
  28984. this.notifyUpdate(kind);
  28985. };
  28986. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28987. if (updateExtends) {
  28988. this.updateExtend(data);
  28989. }
  28990. var meshes = this._meshes;
  28991. var numOfMeshes = meshes.length;
  28992. this._resetPointsArrayCache();
  28993. for (var index = 0; index < numOfMeshes; index++) {
  28994. var mesh = meshes[index];
  28995. if (updateExtends) {
  28996. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28997. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28998. var subMesh = mesh.subMeshes[subIndex];
  28999. subMesh.refreshBoundingInfo();
  29000. }
  29001. }
  29002. }
  29003. };
  29004. Geometry.prototype._bind = function (effect, indexToBind) {
  29005. if (indexToBind === void 0) { indexToBind = undefined; }
  29006. if (indexToBind === undefined) {
  29007. indexToBind = this._indexBuffer;
  29008. }
  29009. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  29010. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  29011. return;
  29012. }
  29013. // Using VAO
  29014. if (!this._vertexArrayObjects[effect.key]) {
  29015. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  29016. }
  29017. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  29018. };
  29019. Geometry.prototype.getTotalVertices = function () {
  29020. if (!this.isReady()) {
  29021. return 0;
  29022. }
  29023. return this._totalVertices;
  29024. };
  29025. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  29026. var vertexBuffer = this.getVertexBuffer(kind);
  29027. if (!vertexBuffer) {
  29028. return null;
  29029. }
  29030. var orig = vertexBuffer.getData();
  29031. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  29032. return orig;
  29033. }
  29034. else {
  29035. var len = orig.length;
  29036. var copy = [];
  29037. for (var i = 0; i < len; i++) {
  29038. copy.push(orig[i]);
  29039. }
  29040. return copy;
  29041. }
  29042. };
  29043. Geometry.prototype.getVertexBuffer = function (kind) {
  29044. if (!this.isReady()) {
  29045. return null;
  29046. }
  29047. return this._vertexBuffers[kind];
  29048. };
  29049. Geometry.prototype.getVertexBuffers = function () {
  29050. if (!this.isReady()) {
  29051. return null;
  29052. }
  29053. return this._vertexBuffers;
  29054. };
  29055. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29056. if (!this._vertexBuffers) {
  29057. if (this._delayInfo) {
  29058. return this._delayInfo.indexOf(kind) !== -1;
  29059. }
  29060. return false;
  29061. }
  29062. return this._vertexBuffers[kind] !== undefined;
  29063. };
  29064. Geometry.prototype.getVerticesDataKinds = function () {
  29065. var result = [];
  29066. var kind;
  29067. if (!this._vertexBuffers && this._delayInfo) {
  29068. for (kind in this._delayInfo) {
  29069. result.push(kind);
  29070. }
  29071. }
  29072. else {
  29073. for (kind in this._vertexBuffers) {
  29074. result.push(kind);
  29075. }
  29076. }
  29077. return result;
  29078. };
  29079. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29080. if (this._indexBuffer) {
  29081. this._engine._releaseBuffer(this._indexBuffer);
  29082. }
  29083. this._disposeVertexArrayObjects();
  29084. this._indices = indices;
  29085. if (this._meshes.length !== 0 && this._indices) {
  29086. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29087. }
  29088. if (totalVertices !== undefined) {
  29089. this._totalVertices = totalVertices;
  29090. }
  29091. var meshes = this._meshes;
  29092. var numOfMeshes = meshes.length;
  29093. for (var index = 0; index < numOfMeshes; index++) {
  29094. meshes[index]._createGlobalSubMesh(true);
  29095. }
  29096. this.notifyUpdate();
  29097. };
  29098. Geometry.prototype.getTotalIndices = function () {
  29099. if (!this.isReady()) {
  29100. return 0;
  29101. }
  29102. return this._indices.length;
  29103. };
  29104. Geometry.prototype.getIndices = function (copyWhenShared) {
  29105. if (!this.isReady()) {
  29106. return null;
  29107. }
  29108. var orig = this._indices;
  29109. if (!copyWhenShared || this._meshes.length === 1) {
  29110. return orig;
  29111. }
  29112. else {
  29113. var len = orig.length;
  29114. var copy = [];
  29115. for (var i = 0; i < len; i++) {
  29116. copy.push(orig[i]);
  29117. }
  29118. return copy;
  29119. }
  29120. };
  29121. Geometry.prototype.getIndexBuffer = function () {
  29122. if (!this.isReady()) {
  29123. return null;
  29124. }
  29125. return this._indexBuffer;
  29126. };
  29127. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29128. if (!effect || !this._vertexArrayObjects) {
  29129. return;
  29130. }
  29131. if (this._vertexArrayObjects[effect.key]) {
  29132. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29133. delete this._vertexArrayObjects[effect.key];
  29134. }
  29135. };
  29136. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29137. var meshes = this._meshes;
  29138. var index = meshes.indexOf(mesh);
  29139. if (index === -1) {
  29140. return;
  29141. }
  29142. meshes.splice(index, 1);
  29143. mesh._geometry = null;
  29144. if (meshes.length === 0 && shouldDispose) {
  29145. this.dispose();
  29146. }
  29147. };
  29148. Geometry.prototype.applyToMesh = function (mesh) {
  29149. if (mesh._geometry === this) {
  29150. return;
  29151. }
  29152. var previousGeometry = mesh._geometry;
  29153. if (previousGeometry) {
  29154. previousGeometry.releaseForMesh(mesh);
  29155. }
  29156. var meshes = this._meshes;
  29157. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29158. mesh._geometry = this;
  29159. this._scene.pushGeometry(this);
  29160. meshes.push(mesh);
  29161. if (this.isReady()) {
  29162. this._applyToMesh(mesh);
  29163. }
  29164. else {
  29165. mesh._boundingInfo = this._boundingInfo;
  29166. }
  29167. };
  29168. Geometry.prototype.updateExtend = function (data, stride) {
  29169. if (data === void 0) { data = null; }
  29170. if (!data) {
  29171. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29172. }
  29173. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29174. };
  29175. Geometry.prototype._applyToMesh = function (mesh) {
  29176. var numOfMeshes = this._meshes.length;
  29177. // vertexBuffers
  29178. for (var kind in this._vertexBuffers) {
  29179. if (numOfMeshes === 1) {
  29180. this._vertexBuffers[kind].create();
  29181. }
  29182. var buffer = this._vertexBuffers[kind].getBuffer();
  29183. if (buffer)
  29184. buffer.references = numOfMeshes;
  29185. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29186. if (!this._extend) {
  29187. this.updateExtend(this._vertexBuffers[kind].getData());
  29188. }
  29189. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29190. mesh._createGlobalSubMesh(false);
  29191. //bounding info was just created again, world matrix should be applied again.
  29192. mesh._updateBoundingInfo();
  29193. }
  29194. }
  29195. // indexBuffer
  29196. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  29197. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29198. }
  29199. if (this._indexBuffer) {
  29200. this._indexBuffer.references = numOfMeshes;
  29201. }
  29202. };
  29203. Geometry.prototype.notifyUpdate = function (kind) {
  29204. if (this.onGeometryUpdated) {
  29205. this.onGeometryUpdated(this, kind);
  29206. }
  29207. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  29208. var mesh = _a[_i];
  29209. mesh._markSubMeshesAsAttributesDirty();
  29210. }
  29211. };
  29212. Geometry.prototype.load = function (scene, onLoaded) {
  29213. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29214. return;
  29215. }
  29216. if (this.isReady()) {
  29217. if (onLoaded) {
  29218. onLoaded();
  29219. }
  29220. return;
  29221. }
  29222. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29223. this._queueLoad(scene, onLoaded);
  29224. };
  29225. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  29226. var _this = this;
  29227. scene._addPendingData(this);
  29228. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29229. _this._delayLoadingFunction(JSON.parse(data), _this);
  29230. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29231. _this._delayInfo = [];
  29232. scene._removePendingData(_this);
  29233. var meshes = _this._meshes;
  29234. var numOfMeshes = meshes.length;
  29235. for (var index = 0; index < numOfMeshes; index++) {
  29236. _this._applyToMesh(meshes[index]);
  29237. }
  29238. if (onLoaded) {
  29239. onLoaded();
  29240. }
  29241. }, function () { }, scene.database);
  29242. };
  29243. /**
  29244. * Invert the geometry to move from a right handed system to a left handed one.
  29245. */
  29246. Geometry.prototype.toLeftHanded = function () {
  29247. // Flip faces
  29248. var tIndices = this.getIndices(false);
  29249. if (tIndices != null && tIndices.length > 0) {
  29250. for (var i = 0; i < tIndices.length; i += 3) {
  29251. var tTemp = tIndices[i + 0];
  29252. tIndices[i + 0] = tIndices[i + 2];
  29253. tIndices[i + 2] = tTemp;
  29254. }
  29255. this.setIndices(tIndices);
  29256. }
  29257. // Negate position.z
  29258. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29259. if (tPositions != null && tPositions.length > 0) {
  29260. for (var i = 0; i < tPositions.length; i += 3) {
  29261. tPositions[i + 2] = -tPositions[i + 2];
  29262. }
  29263. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29264. }
  29265. // Negate normal.z
  29266. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29267. if (tNormals != null && tNormals.length > 0) {
  29268. for (var i = 0; i < tNormals.length; i += 3) {
  29269. tNormals[i + 2] = -tNormals[i + 2];
  29270. }
  29271. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29272. }
  29273. };
  29274. // Cache
  29275. Geometry.prototype._resetPointsArrayCache = function () {
  29276. this._positions = null;
  29277. };
  29278. Geometry.prototype._generatePointsArray = function () {
  29279. if (this._positions)
  29280. return true;
  29281. this._positions = [];
  29282. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29283. if (!data) {
  29284. return false;
  29285. }
  29286. for (var index = 0; index < data.length; index += 3) {
  29287. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29288. }
  29289. return true;
  29290. };
  29291. Geometry.prototype.isDisposed = function () {
  29292. return this._isDisposed;
  29293. };
  29294. Geometry.prototype._disposeVertexArrayObjects = function () {
  29295. if (this._vertexArrayObjects) {
  29296. for (var kind in this._vertexArrayObjects) {
  29297. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29298. }
  29299. this._vertexArrayObjects = {};
  29300. }
  29301. };
  29302. Geometry.prototype.dispose = function () {
  29303. var meshes = this._meshes;
  29304. var numOfMeshes = meshes.length;
  29305. var index;
  29306. for (index = 0; index < numOfMeshes; index++) {
  29307. this.releaseForMesh(meshes[index]);
  29308. }
  29309. this._meshes = [];
  29310. this._disposeVertexArrayObjects();
  29311. for (var kind in this._vertexBuffers) {
  29312. this._vertexBuffers[kind].dispose();
  29313. }
  29314. this._vertexBuffers = {};
  29315. this._totalVertices = 0;
  29316. if (this._indexBuffer) {
  29317. this._engine._releaseBuffer(this._indexBuffer);
  29318. }
  29319. this._indexBuffer = null;
  29320. this._indices = [];
  29321. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29322. this.delayLoadingFile = null;
  29323. this._delayLoadingFunction = null;
  29324. this._delayInfo = [];
  29325. this._boundingInfo = null;
  29326. this._scene.removeGeometry(this);
  29327. this._isDisposed = true;
  29328. };
  29329. Geometry.prototype.copy = function (id) {
  29330. var vertexData = new BABYLON.VertexData();
  29331. vertexData.indices = [];
  29332. var indices = this.getIndices();
  29333. for (var index = 0; index < indices.length; index++) {
  29334. vertexData.indices.push(indices[index]);
  29335. }
  29336. var updatable = false;
  29337. var stopChecking = false;
  29338. var kind;
  29339. for (kind in this._vertexBuffers) {
  29340. // using slice() to make a copy of the array and not just reference it
  29341. var data = this.getVerticesData(kind);
  29342. if (data instanceof Float32Array) {
  29343. vertexData.set(new Float32Array(data), kind);
  29344. }
  29345. else {
  29346. vertexData.set(data.slice(0), kind);
  29347. }
  29348. if (!stopChecking) {
  29349. updatable = this.getVertexBuffer(kind).isUpdatable();
  29350. stopChecking = !updatable;
  29351. }
  29352. }
  29353. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29354. geometry.delayLoadState = this.delayLoadState;
  29355. geometry.delayLoadingFile = this.delayLoadingFile;
  29356. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29357. for (kind in this._delayInfo) {
  29358. geometry._delayInfo = geometry._delayInfo || [];
  29359. geometry._delayInfo.push(kind);
  29360. }
  29361. // Bounding info
  29362. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29363. return geometry;
  29364. };
  29365. Geometry.prototype.serialize = function () {
  29366. var serializationObject = {};
  29367. serializationObject.id = this.id;
  29368. serializationObject.updatable = this._updatable;
  29369. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29370. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29371. }
  29372. return serializationObject;
  29373. };
  29374. Geometry.prototype.toNumberArray = function (origin) {
  29375. if (Array.isArray(origin)) {
  29376. return origin;
  29377. }
  29378. else {
  29379. return Array.prototype.slice.call(origin);
  29380. }
  29381. };
  29382. Geometry.prototype.serializeVerticeData = function () {
  29383. var serializationObject = this.serialize();
  29384. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29385. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29386. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29387. serializationObject.positions._updatable = true;
  29388. }
  29389. }
  29390. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29391. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29392. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29393. serializationObject.normals._updatable = true;
  29394. }
  29395. }
  29396. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29397. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29398. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29399. serializationObject.uvs._updatable = true;
  29400. }
  29401. }
  29402. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29403. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29404. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29405. serializationObject.uv2s._updatable = true;
  29406. }
  29407. }
  29408. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29409. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29410. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29411. serializationObject.uv3s._updatable = true;
  29412. }
  29413. }
  29414. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29415. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29416. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29417. serializationObject.uv4s._updatable = true;
  29418. }
  29419. }
  29420. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29421. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29422. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29423. serializationObject.uv5s._updatable = true;
  29424. }
  29425. }
  29426. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29427. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29428. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29429. serializationObject.uv6s._updatable = true;
  29430. }
  29431. }
  29432. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29433. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29434. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29435. serializationObject.colors._updatable = true;
  29436. }
  29437. }
  29438. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29439. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29440. serializationObject.matricesIndices._isExpanded = true;
  29441. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29442. serializationObject.matricesIndices._updatable = true;
  29443. }
  29444. }
  29445. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29446. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29447. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29448. serializationObject.matricesWeights._updatable = true;
  29449. }
  29450. }
  29451. serializationObject.indices = this.toNumberArray(this.getIndices());
  29452. return serializationObject;
  29453. };
  29454. // Statics
  29455. Geometry.ExtractFromMesh = function (mesh, id) {
  29456. var geometry = mesh._geometry;
  29457. if (!geometry) {
  29458. return null;
  29459. }
  29460. return geometry.copy(id);
  29461. };
  29462. /**
  29463. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29464. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29465. * Be aware Math.random() could cause collisions, but:
  29466. * "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"
  29467. */
  29468. Geometry.RandomId = function () {
  29469. return BABYLON.Tools.RandomId();
  29470. };
  29471. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29472. var scene = mesh.getScene();
  29473. // Geometry
  29474. var geometryId = parsedGeometry.geometryId;
  29475. if (geometryId) {
  29476. var geometry = scene.getGeometryByID(geometryId);
  29477. if (geometry) {
  29478. geometry.applyToMesh(mesh);
  29479. }
  29480. }
  29481. else if (parsedGeometry instanceof ArrayBuffer) {
  29482. var binaryInfo = mesh._binaryInfo;
  29483. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29484. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29485. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29486. }
  29487. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29488. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29489. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29490. }
  29491. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29492. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29493. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29494. }
  29495. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29496. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29497. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29498. }
  29499. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29500. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29501. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29502. }
  29503. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29504. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29505. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29506. }
  29507. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29508. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29509. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29510. }
  29511. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29512. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29513. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29514. }
  29515. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29516. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29517. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29518. }
  29519. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29520. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29521. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29522. }
  29523. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29524. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29525. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29526. }
  29527. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29528. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29529. mesh.setIndices(indicesData);
  29530. }
  29531. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29532. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29533. mesh.subMeshes = [];
  29534. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29535. var materialIndex = subMeshesData[(i * 5) + 0];
  29536. var verticesStart = subMeshesData[(i * 5) + 1];
  29537. var verticesCount = subMeshesData[(i * 5) + 2];
  29538. var indexStart = subMeshesData[(i * 5) + 3];
  29539. var indexCount = subMeshesData[(i * 5) + 4];
  29540. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29541. }
  29542. }
  29543. }
  29544. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29545. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29546. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29547. if (parsedGeometry.uvs) {
  29548. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29549. }
  29550. if (parsedGeometry.uvs2) {
  29551. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29552. }
  29553. if (parsedGeometry.uvs3) {
  29554. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29555. }
  29556. if (parsedGeometry.uvs4) {
  29557. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29558. }
  29559. if (parsedGeometry.uvs5) {
  29560. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29561. }
  29562. if (parsedGeometry.uvs6) {
  29563. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29564. }
  29565. if (parsedGeometry.colors) {
  29566. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29567. }
  29568. if (parsedGeometry.matricesIndices) {
  29569. if (!parsedGeometry.matricesIndices._isExpanded) {
  29570. var floatIndices = [];
  29571. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29572. var matricesIndex = parsedGeometry.matricesIndices[i];
  29573. floatIndices.push(matricesIndex & 0x000000FF);
  29574. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29575. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29576. floatIndices.push(matricesIndex >> 24);
  29577. }
  29578. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29579. }
  29580. else {
  29581. delete parsedGeometry.matricesIndices._isExpanded;
  29582. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29583. }
  29584. }
  29585. if (parsedGeometry.matricesIndicesExtra) {
  29586. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29587. var floatIndices = [];
  29588. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29589. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29590. floatIndices.push(matricesIndex & 0x000000FF);
  29591. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29592. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29593. floatIndices.push(matricesIndex >> 24);
  29594. }
  29595. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29596. }
  29597. else {
  29598. delete parsedGeometry.matricesIndices._isExpanded;
  29599. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29600. }
  29601. }
  29602. if (parsedGeometry.matricesWeights) {
  29603. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29604. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29605. }
  29606. if (parsedGeometry.matricesWeightsExtra) {
  29607. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29608. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29609. }
  29610. mesh.setIndices(parsedGeometry.indices);
  29611. }
  29612. // SubMeshes
  29613. if (parsedGeometry.subMeshes) {
  29614. mesh.subMeshes = [];
  29615. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29616. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29617. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29618. }
  29619. }
  29620. // Flat shading
  29621. if (mesh._shouldGenerateFlatShading) {
  29622. mesh.convertToFlatShadedMesh();
  29623. delete mesh._shouldGenerateFlatShading;
  29624. }
  29625. // Update
  29626. mesh.computeWorldMatrix(true);
  29627. // Octree
  29628. if (scene['_selectionOctree']) {
  29629. scene['_selectionOctree'].addMesh(mesh);
  29630. }
  29631. };
  29632. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29633. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29634. return;
  29635. }
  29636. var size = matricesWeights.length;
  29637. for (var i = 0; i < size; i += influencers) {
  29638. var weight = 0;
  29639. var biggerIndex = i;
  29640. var biggerWeight = 0;
  29641. for (var j = 0; j < influencers - 1; j++) {
  29642. weight += matricesWeights[i + j];
  29643. if (matricesWeights[i + j] > biggerWeight) {
  29644. biggerWeight = matricesWeights[i + j];
  29645. biggerIndex = i + j;
  29646. }
  29647. }
  29648. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29649. }
  29650. };
  29651. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29652. if (scene.getGeometryByID(parsedVertexData.id)) {
  29653. return null; // null since geometry could be something else than a box...
  29654. }
  29655. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29656. if (BABYLON.Tags) {
  29657. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29658. }
  29659. if (parsedVertexData.delayLoadingFile) {
  29660. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29661. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29662. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29663. geometry._delayInfo = [];
  29664. if (parsedVertexData.hasUVs) {
  29665. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29666. }
  29667. if (parsedVertexData.hasUVs2) {
  29668. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29669. }
  29670. if (parsedVertexData.hasUVs3) {
  29671. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29672. }
  29673. if (parsedVertexData.hasUVs4) {
  29674. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29675. }
  29676. if (parsedVertexData.hasUVs5) {
  29677. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29678. }
  29679. if (parsedVertexData.hasUVs6) {
  29680. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29681. }
  29682. if (parsedVertexData.hasColors) {
  29683. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29684. }
  29685. if (parsedVertexData.hasMatricesIndices) {
  29686. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29687. }
  29688. if (parsedVertexData.hasMatricesWeights) {
  29689. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29690. }
  29691. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29692. }
  29693. else {
  29694. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29695. }
  29696. scene.pushGeometry(geometry, true);
  29697. return geometry;
  29698. };
  29699. return Geometry;
  29700. }());
  29701. BABYLON.Geometry = Geometry;
  29702. /////// Primitives //////////////////////////////////////////////
  29703. (function (Geometry) {
  29704. var Primitives;
  29705. (function (Primitives) {
  29706. /// Abstract class
  29707. var _Primitive = (function (_super) {
  29708. __extends(_Primitive, _super);
  29709. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29710. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29711. _this._canBeRegenerated = _canBeRegenerated;
  29712. _this._beingRegenerated = true;
  29713. _this.regenerate();
  29714. _this._beingRegenerated = false;
  29715. return _this;
  29716. }
  29717. _Primitive.prototype.canBeRegenerated = function () {
  29718. return this._canBeRegenerated;
  29719. };
  29720. _Primitive.prototype.regenerate = function () {
  29721. if (!this._canBeRegenerated) {
  29722. return;
  29723. }
  29724. this._beingRegenerated = true;
  29725. this.setAllVerticesData(this._regenerateVertexData(), false);
  29726. this._beingRegenerated = false;
  29727. };
  29728. _Primitive.prototype.asNewGeometry = function (id) {
  29729. return _super.prototype.copy.call(this, id);
  29730. };
  29731. // overrides
  29732. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29733. if (!this._beingRegenerated) {
  29734. return;
  29735. }
  29736. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29737. };
  29738. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29739. if (!this._beingRegenerated) {
  29740. return;
  29741. }
  29742. _super.prototype.setVerticesData.call(this, kind, data, false);
  29743. };
  29744. // to override
  29745. // protected
  29746. _Primitive.prototype._regenerateVertexData = function () {
  29747. throw new Error("Abstract method");
  29748. };
  29749. _Primitive.prototype.copy = function (id) {
  29750. throw new Error("Must be overriden in sub-classes.");
  29751. };
  29752. _Primitive.prototype.serialize = function () {
  29753. var serializationObject = _super.prototype.serialize.call(this);
  29754. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29755. return serializationObject;
  29756. };
  29757. return _Primitive;
  29758. }(Geometry));
  29759. Primitives._Primitive = _Primitive;
  29760. var Ribbon = (function (_super) {
  29761. __extends(Ribbon, _super);
  29762. // Members
  29763. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29764. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29765. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29766. _this.pathArray = pathArray;
  29767. _this.closeArray = closeArray;
  29768. _this.closePath = closePath;
  29769. _this.offset = offset;
  29770. _this.side = side;
  29771. return _this;
  29772. }
  29773. Ribbon.prototype._regenerateVertexData = function () {
  29774. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29775. };
  29776. Ribbon.prototype.copy = function (id) {
  29777. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29778. };
  29779. return Ribbon;
  29780. }(_Primitive));
  29781. Primitives.Ribbon = Ribbon;
  29782. var Box = (function (_super) {
  29783. __extends(Box, _super);
  29784. // Members
  29785. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29786. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29787. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29788. _this.size = size;
  29789. _this.side = side;
  29790. return _this;
  29791. }
  29792. Box.prototype._regenerateVertexData = function () {
  29793. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29794. };
  29795. Box.prototype.copy = function (id) {
  29796. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29797. };
  29798. Box.prototype.serialize = function () {
  29799. var serializationObject = _super.prototype.serialize.call(this);
  29800. serializationObject.size = this.size;
  29801. return serializationObject;
  29802. };
  29803. Box.Parse = function (parsedBox, scene) {
  29804. if (scene.getGeometryByID(parsedBox.id)) {
  29805. return null; // null since geometry could be something else than a box...
  29806. }
  29807. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29808. if (BABYLON.Tags) {
  29809. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29810. }
  29811. scene.pushGeometry(box, true);
  29812. return box;
  29813. };
  29814. return Box;
  29815. }(_Primitive));
  29816. Primitives.Box = Box;
  29817. var Sphere = (function (_super) {
  29818. __extends(Sphere, _super);
  29819. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29821. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29822. _this.segments = segments;
  29823. _this.diameter = diameter;
  29824. _this.side = side;
  29825. return _this;
  29826. }
  29827. Sphere.prototype._regenerateVertexData = function () {
  29828. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29829. };
  29830. Sphere.prototype.copy = function (id) {
  29831. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29832. };
  29833. Sphere.prototype.serialize = function () {
  29834. var serializationObject = _super.prototype.serialize.call(this);
  29835. serializationObject.segments = this.segments;
  29836. serializationObject.diameter = this.diameter;
  29837. return serializationObject;
  29838. };
  29839. Sphere.Parse = function (parsedSphere, scene) {
  29840. if (scene.getGeometryByID(parsedSphere.id)) {
  29841. return null; // null since geometry could be something else than a sphere...
  29842. }
  29843. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29844. if (BABYLON.Tags) {
  29845. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29846. }
  29847. scene.pushGeometry(sphere, true);
  29848. return sphere;
  29849. };
  29850. return Sphere;
  29851. }(_Primitive));
  29852. Primitives.Sphere = Sphere;
  29853. var Disc = (function (_super) {
  29854. __extends(Disc, _super);
  29855. // Members
  29856. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29857. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29858. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29859. _this.radius = radius;
  29860. _this.tessellation = tessellation;
  29861. _this.side = side;
  29862. return _this;
  29863. }
  29864. Disc.prototype._regenerateVertexData = function () {
  29865. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29866. };
  29867. Disc.prototype.copy = function (id) {
  29868. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29869. };
  29870. return Disc;
  29871. }(_Primitive));
  29872. Primitives.Disc = Disc;
  29873. var Cylinder = (function (_super) {
  29874. __extends(Cylinder, _super);
  29875. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29876. if (subdivisions === void 0) { subdivisions = 1; }
  29877. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29878. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29879. _this.height = height;
  29880. _this.diameterTop = diameterTop;
  29881. _this.diameterBottom = diameterBottom;
  29882. _this.tessellation = tessellation;
  29883. _this.subdivisions = subdivisions;
  29884. _this.side = side;
  29885. return _this;
  29886. }
  29887. Cylinder.prototype._regenerateVertexData = function () {
  29888. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29889. };
  29890. Cylinder.prototype.copy = function (id) {
  29891. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29892. };
  29893. Cylinder.prototype.serialize = function () {
  29894. var serializationObject = _super.prototype.serialize.call(this);
  29895. serializationObject.height = this.height;
  29896. serializationObject.diameterTop = this.diameterTop;
  29897. serializationObject.diameterBottom = this.diameterBottom;
  29898. serializationObject.tessellation = this.tessellation;
  29899. return serializationObject;
  29900. };
  29901. Cylinder.Parse = function (parsedCylinder, scene) {
  29902. if (scene.getGeometryByID(parsedCylinder.id)) {
  29903. return null; // null since geometry could be something else than a cylinder...
  29904. }
  29905. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29906. if (BABYLON.Tags) {
  29907. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29908. }
  29909. scene.pushGeometry(cylinder, true);
  29910. return cylinder;
  29911. };
  29912. return Cylinder;
  29913. }(_Primitive));
  29914. Primitives.Cylinder = Cylinder;
  29915. var Torus = (function (_super) {
  29916. __extends(Torus, _super);
  29917. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29918. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29919. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29920. _this.diameter = diameter;
  29921. _this.thickness = thickness;
  29922. _this.tessellation = tessellation;
  29923. _this.side = side;
  29924. return _this;
  29925. }
  29926. Torus.prototype._regenerateVertexData = function () {
  29927. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29928. };
  29929. Torus.prototype.copy = function (id) {
  29930. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29931. };
  29932. Torus.prototype.serialize = function () {
  29933. var serializationObject = _super.prototype.serialize.call(this);
  29934. serializationObject.diameter = this.diameter;
  29935. serializationObject.thickness = this.thickness;
  29936. serializationObject.tessellation = this.tessellation;
  29937. return serializationObject;
  29938. };
  29939. Torus.Parse = function (parsedTorus, scene) {
  29940. if (scene.getGeometryByID(parsedTorus.id)) {
  29941. return null; // null since geometry could be something else than a torus...
  29942. }
  29943. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29944. if (BABYLON.Tags) {
  29945. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29946. }
  29947. scene.pushGeometry(torus, true);
  29948. return torus;
  29949. };
  29950. return Torus;
  29951. }(_Primitive));
  29952. Primitives.Torus = Torus;
  29953. var Ground = (function (_super) {
  29954. __extends(Ground, _super);
  29955. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29956. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29957. _this.width = width;
  29958. _this.height = height;
  29959. _this.subdivisions = subdivisions;
  29960. return _this;
  29961. }
  29962. Ground.prototype._regenerateVertexData = function () {
  29963. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29964. };
  29965. Ground.prototype.copy = function (id) {
  29966. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29967. };
  29968. Ground.prototype.serialize = function () {
  29969. var serializationObject = _super.prototype.serialize.call(this);
  29970. serializationObject.width = this.width;
  29971. serializationObject.height = this.height;
  29972. serializationObject.subdivisions = this.subdivisions;
  29973. return serializationObject;
  29974. };
  29975. Ground.Parse = function (parsedGround, scene) {
  29976. if (scene.getGeometryByID(parsedGround.id)) {
  29977. return null; // null since geometry could be something else than a ground...
  29978. }
  29979. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29980. if (BABYLON.Tags) {
  29981. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29982. }
  29983. scene.pushGeometry(ground, true);
  29984. return ground;
  29985. };
  29986. return Ground;
  29987. }(_Primitive));
  29988. Primitives.Ground = Ground;
  29989. var TiledGround = (function (_super) {
  29990. __extends(TiledGround, _super);
  29991. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29992. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29993. _this.xmin = xmin;
  29994. _this.zmin = zmin;
  29995. _this.xmax = xmax;
  29996. _this.zmax = zmax;
  29997. _this.subdivisions = subdivisions;
  29998. _this.precision = precision;
  29999. return _this;
  30000. }
  30001. TiledGround.prototype._regenerateVertexData = function () {
  30002. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30003. };
  30004. TiledGround.prototype.copy = function (id) {
  30005. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30006. };
  30007. return TiledGround;
  30008. }(_Primitive));
  30009. Primitives.TiledGround = TiledGround;
  30010. var Plane = (function (_super) {
  30011. __extends(Plane, _super);
  30012. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30013. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30014. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30015. _this.size = size;
  30016. _this.side = side;
  30017. return _this;
  30018. }
  30019. Plane.prototype._regenerateVertexData = function () {
  30020. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30021. };
  30022. Plane.prototype.copy = function (id) {
  30023. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30024. };
  30025. Plane.prototype.serialize = function () {
  30026. var serializationObject = _super.prototype.serialize.call(this);
  30027. serializationObject.size = this.size;
  30028. return serializationObject;
  30029. };
  30030. Plane.Parse = function (parsedPlane, scene) {
  30031. if (scene.getGeometryByID(parsedPlane.id)) {
  30032. return null; // null since geometry could be something else than a ground...
  30033. }
  30034. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30035. if (BABYLON.Tags) {
  30036. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30037. }
  30038. scene.pushGeometry(plane, true);
  30039. return plane;
  30040. };
  30041. return Plane;
  30042. }(_Primitive));
  30043. Primitives.Plane = Plane;
  30044. var TorusKnot = (function (_super) {
  30045. __extends(TorusKnot, _super);
  30046. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30047. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30048. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30049. _this.radius = radius;
  30050. _this.tube = tube;
  30051. _this.radialSegments = radialSegments;
  30052. _this.tubularSegments = tubularSegments;
  30053. _this.p = p;
  30054. _this.q = q;
  30055. _this.side = side;
  30056. return _this;
  30057. }
  30058. TorusKnot.prototype._regenerateVertexData = function () {
  30059. 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 });
  30060. };
  30061. TorusKnot.prototype.copy = function (id) {
  30062. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30063. };
  30064. TorusKnot.prototype.serialize = function () {
  30065. var serializationObject = _super.prototype.serialize.call(this);
  30066. serializationObject.radius = this.radius;
  30067. serializationObject.tube = this.tube;
  30068. serializationObject.radialSegments = this.radialSegments;
  30069. serializationObject.tubularSegments = this.tubularSegments;
  30070. serializationObject.p = this.p;
  30071. serializationObject.q = this.q;
  30072. return serializationObject;
  30073. };
  30074. ;
  30075. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30076. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30077. return null; // null since geometry could be something else than a ground...
  30078. }
  30079. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30080. if (BABYLON.Tags) {
  30081. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30082. }
  30083. scene.pushGeometry(torusKnot, true);
  30084. return torusKnot;
  30085. };
  30086. return TorusKnot;
  30087. }(_Primitive));
  30088. Primitives.TorusKnot = TorusKnot;
  30089. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30090. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30091. })(BABYLON || (BABYLON = {}));
  30092. //# sourceMappingURL=babylon.geometry.js.map
  30093. var BABYLON;
  30094. (function (BABYLON) {
  30095. var PostProcessManager = (function () {
  30096. function PostProcessManager(scene) {
  30097. this._vertexBuffers = {};
  30098. this._scene = scene;
  30099. }
  30100. PostProcessManager.prototype._prepareBuffers = function () {
  30101. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30102. return;
  30103. }
  30104. // VBO
  30105. var vertices = [];
  30106. vertices.push(1, 1);
  30107. vertices.push(-1, 1);
  30108. vertices.push(-1, -1);
  30109. vertices.push(1, -1);
  30110. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30111. this._buildIndexBuffer();
  30112. };
  30113. PostProcessManager.prototype._buildIndexBuffer = function () {
  30114. // Indices
  30115. var indices = [];
  30116. indices.push(0);
  30117. indices.push(1);
  30118. indices.push(2);
  30119. indices.push(0);
  30120. indices.push(2);
  30121. indices.push(3);
  30122. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30123. };
  30124. PostProcessManager.prototype._rebuild = function () {
  30125. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30126. return;
  30127. }
  30128. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  30129. this._buildIndexBuffer();
  30130. };
  30131. // Methods
  30132. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  30133. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30134. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30135. return false;
  30136. }
  30137. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  30138. return true;
  30139. };
  30140. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  30141. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30142. var engine = this._scene.getEngine();
  30143. for (var index = 0; index < postProcesses.length; index++) {
  30144. if (index < postProcesses.length - 1) {
  30145. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30146. }
  30147. else {
  30148. if (targetTexture) {
  30149. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  30150. }
  30151. else {
  30152. engine.restoreDefaultFramebuffer();
  30153. }
  30154. }
  30155. var pp = postProcesses[index];
  30156. var effect = pp.apply();
  30157. if (effect) {
  30158. pp.onBeforeRenderObservable.notifyObservers(effect);
  30159. // VBOs
  30160. this._prepareBuffers();
  30161. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30162. // Draw order
  30163. engine.draw(true, 0, 6);
  30164. pp.onAfterRenderObservable.notifyObservers(effect);
  30165. }
  30166. }
  30167. // Restore depth buffer
  30168. engine.setDepthBuffer(true);
  30169. engine.setDepthWrite(true);
  30170. };
  30171. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  30172. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30173. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30174. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30175. return;
  30176. }
  30177. var engine = this._scene.getEngine();
  30178. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30179. if (index < len - 1) {
  30180. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30181. }
  30182. else {
  30183. if (targetTexture) {
  30184. engine.bindFramebuffer(targetTexture, faceIndex, null, null, forceFullscreenViewport);
  30185. }
  30186. else {
  30187. engine.restoreDefaultFramebuffer();
  30188. }
  30189. }
  30190. if (doNotPresent) {
  30191. break;
  30192. }
  30193. var pp = postProcesses[index];
  30194. var effect = pp.apply();
  30195. if (effect) {
  30196. pp.onBeforeRenderObservable.notifyObservers(effect);
  30197. // VBOs
  30198. this._prepareBuffers();
  30199. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30200. // Draw order
  30201. engine.draw(true, 0, 6);
  30202. pp.onAfterRenderObservable.notifyObservers(effect);
  30203. }
  30204. }
  30205. // Restore states
  30206. engine.setDepthBuffer(true);
  30207. engine.setDepthWrite(true);
  30208. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30209. };
  30210. PostProcessManager.prototype.dispose = function () {
  30211. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30212. if (buffer) {
  30213. buffer.dispose();
  30214. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30215. }
  30216. if (this._indexBuffer) {
  30217. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30218. this._indexBuffer = null;
  30219. }
  30220. };
  30221. return PostProcessManager;
  30222. }());
  30223. BABYLON.PostProcessManager = PostProcessManager;
  30224. })(BABYLON || (BABYLON = {}));
  30225. //# sourceMappingURL=babylon.postProcessManager.js.map
  30226. var BABYLON;
  30227. (function (BABYLON) {
  30228. /**
  30229. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  30230. */
  30231. var PerformanceMonitor = (function () {
  30232. /**
  30233. * constructor
  30234. * @param frameSampleSize The number of samples required to saturate the sliding window
  30235. */
  30236. function PerformanceMonitor(frameSampleSize) {
  30237. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  30238. this._enabled = true;
  30239. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  30240. }
  30241. /**
  30242. * Samples current frame
  30243. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  30244. */
  30245. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  30246. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  30247. if (!this._enabled)
  30248. return;
  30249. if (this._lastFrameTimeMs != null) {
  30250. var dt = timeMs - this._lastFrameTimeMs;
  30251. this._rollingFrameTime.add(dt);
  30252. }
  30253. this._lastFrameTimeMs = timeMs;
  30254. };
  30255. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30256. /**
  30257. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30258. * @return Average frame time in milliseconds
  30259. */
  30260. get: function () {
  30261. return this._rollingFrameTime.average;
  30262. },
  30263. enumerable: true,
  30264. configurable: true
  30265. });
  30266. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30267. /**
  30268. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30269. * @return Frame time variance in milliseconds squared
  30270. */
  30271. get: function () {
  30272. return this._rollingFrameTime.variance;
  30273. },
  30274. enumerable: true,
  30275. configurable: true
  30276. });
  30277. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30278. /**
  30279. * Returns the frame time of the most recent frame
  30280. * @return Frame time in milliseconds
  30281. */
  30282. get: function () {
  30283. return this._rollingFrameTime.history(0);
  30284. },
  30285. enumerable: true,
  30286. configurable: true
  30287. });
  30288. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30289. /**
  30290. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30291. * @return Framerate in frames per second
  30292. */
  30293. get: function () {
  30294. return 1000.0 / this._rollingFrameTime.average;
  30295. },
  30296. enumerable: true,
  30297. configurable: true
  30298. });
  30299. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30300. /**
  30301. * Returns the average framerate in frames per second using the most recent frame time
  30302. * @return Framerate in frames per second
  30303. */
  30304. get: function () {
  30305. return 1000.0 / this._rollingFrameTime.history(0);
  30306. },
  30307. enumerable: true,
  30308. configurable: true
  30309. });
  30310. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30311. /**
  30312. * Returns true if enough samples have been taken to completely fill the sliding window
  30313. * @return true if saturated
  30314. */
  30315. get: function () {
  30316. return this._rollingFrameTime.isSaturated();
  30317. },
  30318. enumerable: true,
  30319. configurable: true
  30320. });
  30321. /**
  30322. * Enables contributions to the sliding window sample set
  30323. */
  30324. PerformanceMonitor.prototype.enable = function () {
  30325. this._enabled = true;
  30326. };
  30327. /**
  30328. * Disables contributions to the sliding window sample set
  30329. * Samples will not be interpolated over the disabled period
  30330. */
  30331. PerformanceMonitor.prototype.disable = function () {
  30332. this._enabled = false;
  30333. //clear last sample to avoid interpolating over the disabled period when next enabled
  30334. this._lastFrameTimeMs = null;
  30335. this._lastChangeTimeMs = null;
  30336. };
  30337. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30338. /**
  30339. * Returns true if sampling is enabled
  30340. * @return true if enabled
  30341. */
  30342. get: function () {
  30343. return this._enabled;
  30344. },
  30345. enumerable: true,
  30346. configurable: true
  30347. });
  30348. /**
  30349. * Resets performance monitor
  30350. */
  30351. PerformanceMonitor.prototype.reset = function () {
  30352. //clear last sample to avoid interpolating over the disabled period when next enabled
  30353. this._lastFrameTimeMs = null;
  30354. this._lastChangeTimeMs = null;
  30355. //wipe record
  30356. this._rollingFrameTime.reset();
  30357. };
  30358. return PerformanceMonitor;
  30359. }());
  30360. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30361. /**
  30362. * RollingAverage
  30363. *
  30364. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30365. */
  30366. var RollingAverage = (function () {
  30367. /**
  30368. * constructor
  30369. * @param length The number of samples required to saturate the sliding window
  30370. */
  30371. function RollingAverage(length) {
  30372. this._samples = new Array(length);
  30373. this.reset();
  30374. }
  30375. /**
  30376. * Adds a sample to the sample set
  30377. * @param v The sample value
  30378. */
  30379. RollingAverage.prototype.add = function (v) {
  30380. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30381. var delta;
  30382. //we need to check if we've already wrapped round
  30383. if (this.isSaturated()) {
  30384. //remove bottom of stack from mean
  30385. var bottomValue = this._samples[this._pos];
  30386. delta = bottomValue - this.average;
  30387. this.average -= delta / (this._sampleCount - 1);
  30388. this._m2 -= delta * (bottomValue - this.average);
  30389. }
  30390. else {
  30391. this._sampleCount++;
  30392. }
  30393. //add new value to mean
  30394. delta = v - this.average;
  30395. this.average += delta / (this._sampleCount);
  30396. this._m2 += delta * (v - this.average);
  30397. //set the new variance
  30398. this.variance = this._m2 / (this._sampleCount - 1);
  30399. this._samples[this._pos] = v;
  30400. this._pos++;
  30401. this._pos %= this._samples.length; //positive wrap around
  30402. };
  30403. /**
  30404. * Returns previously added values or null if outside of history or outside the sliding window domain
  30405. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30406. * @return Value previously recorded with add() or null if outside of range
  30407. */
  30408. RollingAverage.prototype.history = function (i) {
  30409. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30410. return null;
  30411. }
  30412. var i0 = this._wrapPosition(this._pos - 1.0);
  30413. return this._samples[this._wrapPosition(i0 - i)];
  30414. };
  30415. /**
  30416. * Returns true if enough samples have been taken to completely fill the sliding window
  30417. * @return true if sample-set saturated
  30418. */
  30419. RollingAverage.prototype.isSaturated = function () {
  30420. return this._sampleCount >= this._samples.length;
  30421. };
  30422. /**
  30423. * Resets the rolling average (equivalent to 0 samples taken so far)
  30424. */
  30425. RollingAverage.prototype.reset = function () {
  30426. this.average = 0;
  30427. this.variance = 0;
  30428. this._sampleCount = 0;
  30429. this._pos = 0;
  30430. this._m2 = 0;
  30431. };
  30432. /**
  30433. * Wraps a value around the sample range boundaries
  30434. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30435. * @return Wrapped position in sample range
  30436. */
  30437. RollingAverage.prototype._wrapPosition = function (i) {
  30438. var max = this._samples.length;
  30439. return ((i % max) + max) % max;
  30440. };
  30441. return RollingAverage;
  30442. }());
  30443. BABYLON.RollingAverage = RollingAverage;
  30444. })(BABYLON || (BABYLON = {}));
  30445. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30446. var BABYLON;
  30447. (function (BABYLON) {
  30448. var StandardMaterialDefines = (function (_super) {
  30449. __extends(StandardMaterialDefines, _super);
  30450. function StandardMaterialDefines() {
  30451. var _this = _super.call(this) || this;
  30452. _this.MAINUV1 = false;
  30453. _this.MAINUV2 = false;
  30454. _this.DIFFUSE = false;
  30455. _this.DIFFUSEDIRECTUV = 0;
  30456. _this.AMBIENT = false;
  30457. _this.AMBIENTDIRECTUV = 0;
  30458. _this.OPACITY = false;
  30459. _this.OPACITYDIRECTUV = 0;
  30460. _this.OPACITYRGB = false;
  30461. _this.REFLECTION = false;
  30462. _this.EMISSIVE = false;
  30463. _this.EMISSIVEDIRECTUV = 0;
  30464. _this.SPECULAR = false;
  30465. _this.SPECULARDIRECTUV = 0;
  30466. _this.BUMP = false;
  30467. _this.BUMPDIRECTUV = 0;
  30468. _this.PARALLAX = false;
  30469. _this.PARALLAXOCCLUSION = false;
  30470. _this.SPECULAROVERALPHA = false;
  30471. _this.CLIPPLANE = false;
  30472. _this.ALPHATEST = false;
  30473. _this.DEPTHPREPASS = false;
  30474. _this.ALPHAFROMDIFFUSE = false;
  30475. _this.POINTSIZE = false;
  30476. _this.FOG = false;
  30477. _this.SPECULARTERM = false;
  30478. _this.DIFFUSEFRESNEL = false;
  30479. _this.OPACITYFRESNEL = false;
  30480. _this.REFLECTIONFRESNEL = false;
  30481. _this.REFRACTIONFRESNEL = false;
  30482. _this.EMISSIVEFRESNEL = false;
  30483. _this.FRESNEL = false;
  30484. _this.NORMAL = false;
  30485. _this.UV1 = false;
  30486. _this.UV2 = false;
  30487. _this.VERTEXCOLOR = false;
  30488. _this.VERTEXALPHA = false;
  30489. _this.NUM_BONE_INFLUENCERS = 0;
  30490. _this.BonesPerMesh = 0;
  30491. _this.INSTANCES = false;
  30492. _this.GLOSSINESS = false;
  30493. _this.ROUGHNESS = false;
  30494. _this.EMISSIVEASILLUMINATION = false;
  30495. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30496. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30497. _this.LIGHTMAP = false;
  30498. _this.LIGHTMAPDIRECTUV = 0;
  30499. _this.USELIGHTMAPASSHADOWMAP = false;
  30500. _this.REFLECTIONMAP_3D = false;
  30501. _this.REFLECTIONMAP_SPHERICAL = false;
  30502. _this.REFLECTIONMAP_PLANAR = false;
  30503. _this.REFLECTIONMAP_CUBIC = false;
  30504. _this.REFLECTIONMAP_PROJECTION = false;
  30505. _this.REFLECTIONMAP_SKYBOX = false;
  30506. _this.REFLECTIONMAP_EXPLICIT = false;
  30507. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30508. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30509. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30510. _this.INVERTCUBICMAP = false;
  30511. _this.LOGARITHMICDEPTH = false;
  30512. _this.REFRACTION = false;
  30513. _this.REFRACTIONMAP_3D = false;
  30514. _this.REFLECTIONOVERALPHA = false;
  30515. _this.TWOSIDEDLIGHTING = false;
  30516. _this.SHADOWFLOAT = false;
  30517. _this.MORPHTARGETS = false;
  30518. _this.MORPHTARGETS_NORMAL = false;
  30519. _this.MORPHTARGETS_TANGENT = false;
  30520. _this.NUM_MORPH_INFLUENCERS = 0;
  30521. _this.USERIGHTHANDEDSYSTEM = false;
  30522. _this.IMAGEPROCESSING = false;
  30523. _this.VIGNETTE = false;
  30524. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30525. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30526. _this.TONEMAPPING = false;
  30527. _this.CONTRAST = false;
  30528. _this.COLORCURVES = false;
  30529. _this.COLORGRADING = false;
  30530. _this.SAMPLER3DGREENDEPTH = false;
  30531. _this.SAMPLER3DBGRMAP = false;
  30532. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30533. _this.EXPOSURE = false;
  30534. _this.rebuild();
  30535. return _this;
  30536. }
  30537. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30538. var modes = [
  30539. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30540. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30541. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30542. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30543. ];
  30544. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30545. var mode = modes_1[_i];
  30546. this[mode] = (mode === modeToEnable);
  30547. }
  30548. };
  30549. return StandardMaterialDefines;
  30550. }(BABYLON.MaterialDefines));
  30551. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30552. var StandardMaterial = (function (_super) {
  30553. __extends(StandardMaterial, _super);
  30554. function StandardMaterial(name, scene) {
  30555. var _this = _super.call(this, name, scene) || this;
  30556. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30557. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30558. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30559. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30560. _this.specularPower = 64;
  30561. _this._useAlphaFromDiffuseTexture = false;
  30562. _this._useEmissiveAsIllumination = false;
  30563. _this._linkEmissiveWithDiffuse = false;
  30564. _this._useSpecularOverAlpha = false;
  30565. _this._useReflectionOverAlpha = false;
  30566. _this._disableLighting = false;
  30567. _this._useParallax = false;
  30568. _this._useParallaxOcclusion = false;
  30569. _this.parallaxScaleBias = 0.05;
  30570. _this._roughness = 0;
  30571. _this.indexOfRefraction = 0.98;
  30572. _this.invertRefractionY = true;
  30573. _this._useLightmapAsShadowmap = false;
  30574. _this._useReflectionFresnelFromSpecular = false;
  30575. _this._useGlossinessFromSpecularMapAlpha = false;
  30576. _this._maxSimultaneousLights = 4;
  30577. /**
  30578. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30579. */
  30580. _this._invertNormalMapX = false;
  30581. /**
  30582. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30583. */
  30584. _this._invertNormalMapY = false;
  30585. /**
  30586. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30587. */
  30588. _this._twoSidedLighting = false;
  30589. _this._renderTargets = new BABYLON.SmartArray(16);
  30590. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30591. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30592. // Setup the default processing configuration to the scene.
  30593. _this._attachImageProcessingConfiguration(null);
  30594. _this.getRenderTargetTextures = function () {
  30595. _this._renderTargets.reset();
  30596. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30597. _this._renderTargets.push(_this._reflectionTexture);
  30598. }
  30599. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30600. _this._renderTargets.push(_this._refractionTexture);
  30601. }
  30602. return _this._renderTargets;
  30603. };
  30604. return _this;
  30605. }
  30606. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  30607. /**
  30608. * Gets the image processing configuration used either in this material.
  30609. */
  30610. get: function () {
  30611. return this._imageProcessingConfiguration;
  30612. },
  30613. /**
  30614. * Sets the Default image processing configuration used either in the this material.
  30615. *
  30616. * If sets to null, the scene one is in use.
  30617. */
  30618. set: function (value) {
  30619. this._attachImageProcessingConfiguration(value);
  30620. // Ensure the effect will be rebuilt.
  30621. this._markAllSubMeshesAsTexturesDirty();
  30622. },
  30623. enumerable: true,
  30624. configurable: true
  30625. });
  30626. /**
  30627. * Attaches a new image processing configuration to the Standard Material.
  30628. * @param configuration
  30629. */
  30630. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30631. var _this = this;
  30632. if (configuration === this._imageProcessingConfiguration) {
  30633. return;
  30634. }
  30635. // Detaches observer.
  30636. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30637. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30638. }
  30639. // Pick the scene configuration if needed.
  30640. if (!configuration) {
  30641. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30642. }
  30643. else {
  30644. this._imageProcessingConfiguration = configuration;
  30645. }
  30646. // Attaches observer.
  30647. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30648. _this._markAllSubMeshesAsImageProcessingDirty();
  30649. });
  30650. };
  30651. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  30652. /**
  30653. * Gets wether the color curves effect is enabled.
  30654. */
  30655. get: function () {
  30656. return this.imageProcessingConfiguration.colorCurvesEnabled;
  30657. },
  30658. /**
  30659. * Sets wether the color curves effect is enabled.
  30660. */
  30661. set: function (value) {
  30662. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  30663. },
  30664. enumerable: true,
  30665. configurable: true
  30666. });
  30667. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  30668. /**
  30669. * Gets wether the color grading effect is enabled.
  30670. */
  30671. get: function () {
  30672. return this.imageProcessingConfiguration.colorGradingEnabled;
  30673. },
  30674. /**
  30675. * Gets wether the color grading effect is enabled.
  30676. */
  30677. set: function (value) {
  30678. this.imageProcessingConfiguration.colorGradingEnabled = value;
  30679. },
  30680. enumerable: true,
  30681. configurable: true
  30682. });
  30683. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  30684. /**
  30685. * Gets wether tonemapping is enabled or not.
  30686. */
  30687. get: function () {
  30688. return this._imageProcessingConfiguration.toneMappingEnabled;
  30689. },
  30690. /**
  30691. * Sets wether tonemapping is enabled or not
  30692. */
  30693. set: function (value) {
  30694. this._imageProcessingConfiguration.toneMappingEnabled = value;
  30695. },
  30696. enumerable: true,
  30697. configurable: true
  30698. });
  30699. ;
  30700. ;
  30701. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  30702. /**
  30703. * The camera exposure used on this material.
  30704. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30705. * This corresponds to a photographic exposure.
  30706. */
  30707. get: function () {
  30708. return this._imageProcessingConfiguration.exposure;
  30709. },
  30710. /**
  30711. * The camera exposure used on this material.
  30712. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30713. * This corresponds to a photographic exposure.
  30714. */
  30715. set: function (value) {
  30716. this._imageProcessingConfiguration.exposure = value;
  30717. },
  30718. enumerable: true,
  30719. configurable: true
  30720. });
  30721. ;
  30722. ;
  30723. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  30724. /**
  30725. * Gets The camera contrast used on this material.
  30726. */
  30727. get: function () {
  30728. return this._imageProcessingConfiguration.contrast;
  30729. },
  30730. /**
  30731. * Sets The camera contrast used on this material.
  30732. */
  30733. set: function (value) {
  30734. this._imageProcessingConfiguration.contrast = value;
  30735. },
  30736. enumerable: true,
  30737. configurable: true
  30738. });
  30739. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  30740. /**
  30741. * Gets the Color Grading 2D Lookup Texture.
  30742. */
  30743. get: function () {
  30744. return this._imageProcessingConfiguration.colorGradingTexture;
  30745. },
  30746. /**
  30747. * Sets the Color Grading 2D Lookup Texture.
  30748. */
  30749. set: function (value) {
  30750. this._imageProcessingConfiguration.colorGradingTexture = value;
  30751. },
  30752. enumerable: true,
  30753. configurable: true
  30754. });
  30755. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  30756. /**
  30757. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30758. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30759. * 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;
  30760. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30761. */
  30762. get: function () {
  30763. return this._imageProcessingConfiguration.colorCurves;
  30764. },
  30765. /**
  30766. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30767. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30768. * 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;
  30769. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30770. */
  30771. set: function (value) {
  30772. this._imageProcessingConfiguration.colorCurves = value;
  30773. },
  30774. enumerable: true,
  30775. configurable: true
  30776. });
  30777. StandardMaterial.prototype.getClassName = function () {
  30778. return "StandardMaterial";
  30779. };
  30780. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30781. get: function () {
  30782. return this._useLogarithmicDepth;
  30783. },
  30784. set: function (value) {
  30785. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30786. this._markAllSubMeshesAsMiscDirty();
  30787. },
  30788. enumerable: true,
  30789. configurable: true
  30790. });
  30791. StandardMaterial.prototype.needAlphaBlending = function () {
  30792. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  30793. };
  30794. StandardMaterial.prototype.needAlphaTesting = function () {
  30795. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  30796. };
  30797. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30798. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  30799. };
  30800. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30801. return this._diffuseTexture;
  30802. };
  30803. /**
  30804. * Child classes can use it to update shaders
  30805. */
  30806. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30807. if (this.isFrozen) {
  30808. if (this._wasPreviouslyReady && subMesh.effect) {
  30809. return true;
  30810. }
  30811. }
  30812. if (!subMesh._materialDefines) {
  30813. subMesh._materialDefines = new StandardMaterialDefines();
  30814. }
  30815. var scene = this.getScene();
  30816. var defines = subMesh._materialDefines;
  30817. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30818. if (defines._renderId === scene.getRenderId()) {
  30819. return true;
  30820. }
  30821. }
  30822. var engine = scene.getEngine();
  30823. // Lights
  30824. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30825. // Textures
  30826. if (defines._areTexturesDirty) {
  30827. defines._needUVs = false;
  30828. defines.MAINUV1 = false;
  30829. defines.MAINUV2 = false;
  30830. if (scene.texturesEnabled) {
  30831. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30832. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  30833. return false;
  30834. }
  30835. else {
  30836. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  30837. }
  30838. }
  30839. else {
  30840. defines.DIFFUSE = false;
  30841. }
  30842. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30843. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30844. return false;
  30845. }
  30846. else {
  30847. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  30848. }
  30849. }
  30850. else {
  30851. defines.AMBIENT = false;
  30852. }
  30853. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30854. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30855. return false;
  30856. }
  30857. else {
  30858. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  30859. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  30860. }
  30861. }
  30862. else {
  30863. defines.OPACITY = false;
  30864. }
  30865. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30866. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  30867. return false;
  30868. }
  30869. else {
  30870. defines._needNormals = true;
  30871. defines.REFLECTION = true;
  30872. defines.ROUGHNESS = (this._roughness > 0);
  30873. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  30874. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  30875. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  30876. switch (this._reflectionTexture.coordinatesMode) {
  30877. case BABYLON.Texture.CUBIC_MODE:
  30878. case BABYLON.Texture.INVCUBIC_MODE:
  30879. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  30880. break;
  30881. case BABYLON.Texture.EXPLICIT_MODE:
  30882. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  30883. break;
  30884. case BABYLON.Texture.PLANAR_MODE:
  30885. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  30886. break;
  30887. case BABYLON.Texture.PROJECTION_MODE:
  30888. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  30889. break;
  30890. case BABYLON.Texture.SKYBOX_MODE:
  30891. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  30892. break;
  30893. case BABYLON.Texture.SPHERICAL_MODE:
  30894. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  30895. break;
  30896. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30897. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  30898. break;
  30899. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30900. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  30901. break;
  30902. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30903. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  30904. break;
  30905. }
  30906. }
  30907. }
  30908. else {
  30909. defines.REFLECTION = false;
  30910. }
  30911. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30912. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30913. return false;
  30914. }
  30915. else {
  30916. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  30917. }
  30918. }
  30919. else {
  30920. defines.EMISSIVE = false;
  30921. }
  30922. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30923. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30924. return false;
  30925. }
  30926. else {
  30927. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  30928. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30929. }
  30930. }
  30931. else {
  30932. defines.LIGHTMAP = false;
  30933. }
  30934. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30935. if (!this._specularTexture.isReadyOrNotBlocking()) {
  30936. return false;
  30937. }
  30938. else {
  30939. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  30940. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  30941. }
  30942. }
  30943. else {
  30944. defines.SPECULAR = false;
  30945. }
  30946. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30947. // Bump texure can not be not blocking.
  30948. if (!this._bumpTexture.isReady()) {
  30949. return false;
  30950. }
  30951. else {
  30952. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  30953. defines.PARALLAX = this._useParallax;
  30954. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  30955. }
  30956. }
  30957. else {
  30958. defines.BUMP = false;
  30959. }
  30960. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30961. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30962. return false;
  30963. }
  30964. else {
  30965. defines._needUVs = true;
  30966. defines.REFRACTION = true;
  30967. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30968. }
  30969. }
  30970. else {
  30971. defines.REFRACTION = false;
  30972. }
  30973. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  30974. }
  30975. else {
  30976. defines.DIFFUSE = false;
  30977. defines.AMBIENT = false;
  30978. defines.OPACITY = false;
  30979. defines.REFLECTION = false;
  30980. defines.EMISSIVE = false;
  30981. defines.LIGHTMAP = false;
  30982. defines.BUMP = false;
  30983. defines.REFRACTION = false;
  30984. }
  30985. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  30986. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  30987. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  30988. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  30989. }
  30990. if (defines._areImageProcessingDirty) {
  30991. if (!this._imageProcessingConfiguration.isReady()) {
  30992. return false;
  30993. }
  30994. this._imageProcessingConfiguration.prepareDefines(defines);
  30995. }
  30996. if (defines._areFresnelDirty) {
  30997. if (StandardMaterial.FresnelEnabled) {
  30998. // Fresnel
  30999. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  31000. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  31001. this._reflectionFresnelParameters) {
  31002. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  31003. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  31004. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  31005. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  31006. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  31007. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  31008. defines._needNormals = true;
  31009. defines.FRESNEL = true;
  31010. }
  31011. }
  31012. else {
  31013. defines.FRESNEL = false;
  31014. }
  31015. }
  31016. // Misc.
  31017. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  31018. // Attribs
  31019. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  31020. // Values that need to be evaluated on every frame
  31021. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  31022. // Get correct effect
  31023. if (defines.isDirty) {
  31024. defines.markAsProcessed();
  31025. scene.resetCachedMaterial();
  31026. // Fallbacks
  31027. var fallbacks = new BABYLON.EffectFallbacks();
  31028. if (defines.REFLECTION) {
  31029. fallbacks.addFallback(0, "REFLECTION");
  31030. }
  31031. if (defines.SPECULAR) {
  31032. fallbacks.addFallback(0, "SPECULAR");
  31033. }
  31034. if (defines.BUMP) {
  31035. fallbacks.addFallback(0, "BUMP");
  31036. }
  31037. if (defines.PARALLAX) {
  31038. fallbacks.addFallback(1, "PARALLAX");
  31039. }
  31040. if (defines.PARALLAXOCCLUSION) {
  31041. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31042. }
  31043. if (defines.SPECULAROVERALPHA) {
  31044. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31045. }
  31046. if (defines.FOG) {
  31047. fallbacks.addFallback(1, "FOG");
  31048. }
  31049. if (defines.POINTSIZE) {
  31050. fallbacks.addFallback(0, "POINTSIZE");
  31051. }
  31052. if (defines.LOGARITHMICDEPTH) {
  31053. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31054. }
  31055. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31056. if (defines.SPECULARTERM) {
  31057. fallbacks.addFallback(0, "SPECULARTERM");
  31058. }
  31059. if (defines.DIFFUSEFRESNEL) {
  31060. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  31061. }
  31062. if (defines.OPACITYFRESNEL) {
  31063. fallbacks.addFallback(2, "OPACITYFRESNEL");
  31064. }
  31065. if (defines.REFLECTIONFRESNEL) {
  31066. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  31067. }
  31068. if (defines.EMISSIVEFRESNEL) {
  31069. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  31070. }
  31071. if (defines.FRESNEL) {
  31072. fallbacks.addFallback(4, "FRESNEL");
  31073. }
  31074. //Attributes
  31075. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31076. if (defines.NORMAL) {
  31077. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31078. }
  31079. if (defines.UV1) {
  31080. attribs.push(BABYLON.VertexBuffer.UVKind);
  31081. }
  31082. if (defines.UV2) {
  31083. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31084. }
  31085. if (defines.VERTEXCOLOR) {
  31086. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31087. }
  31088. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31089. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31090. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  31091. var shaderName = "default";
  31092. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  31093. "vFogInfos", "vFogColor", "pointSize",
  31094. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31095. "mBones",
  31096. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31097. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  31098. "logarithmicDepthConstant", "vNormalReoderParams"
  31099. ];
  31100. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  31101. var uniformBuffers = ["Material", "Scene"];
  31102. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  31103. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  31104. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  31105. uniformsNames: uniforms,
  31106. uniformBuffersNames: uniformBuffers,
  31107. samplers: samplers,
  31108. defines: defines,
  31109. maxSimultaneousLights: this._maxSimultaneousLights
  31110. });
  31111. if (this.customShaderNameResolve) {
  31112. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  31113. }
  31114. var join = defines.toString();
  31115. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  31116. attributes: attribs,
  31117. uniformsNames: uniforms,
  31118. uniformBuffersNames: uniformBuffers,
  31119. samplers: samplers,
  31120. defines: join,
  31121. fallbacks: fallbacks,
  31122. onCompiled: this.onCompiled,
  31123. onError: this.onError,
  31124. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31125. }, engine), defines);
  31126. this.buildUniformLayout();
  31127. }
  31128. if (!subMesh.effect.isReady()) {
  31129. return false;
  31130. }
  31131. defines._renderId = scene.getRenderId();
  31132. this._wasPreviouslyReady = true;
  31133. return true;
  31134. };
  31135. StandardMaterial.prototype.buildUniformLayout = function () {
  31136. // Order is important !
  31137. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  31138. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  31139. this._uniformBuffer.addUniform("opacityParts", 4);
  31140. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  31141. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  31142. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  31143. this._uniformBuffer.addUniform("refractionRightColor", 4);
  31144. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  31145. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  31146. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  31147. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  31148. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31149. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31150. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31151. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31152. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  31153. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31154. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  31155. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31156. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31157. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31158. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31159. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31160. this._uniformBuffer.addUniform("specularMatrix", 16);
  31161. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31162. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  31163. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31164. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31165. this._uniformBuffer.addUniform("vSpecularColor", 4);
  31166. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31167. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  31168. this._uniformBuffer.addUniform("pointSize", 1);
  31169. this._uniformBuffer.create();
  31170. };
  31171. StandardMaterial.prototype.unbind = function () {
  31172. if (this._activeEffect) {
  31173. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31174. this._activeEffect.setTexture("reflection2DSampler", null);
  31175. }
  31176. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31177. this._activeEffect.setTexture("refraction2DSampler", null);
  31178. }
  31179. }
  31180. _super.prototype.unbind.call(this);
  31181. };
  31182. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31183. var scene = this.getScene();
  31184. var defines = subMesh._materialDefines;
  31185. if (!defines) {
  31186. return;
  31187. }
  31188. var effect = subMesh.effect;
  31189. this._activeEffect = effect;
  31190. // Matrices
  31191. this.bindOnlyWorldMatrix(world);
  31192. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  31193. // Bones
  31194. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  31195. if (mustRebind) {
  31196. this._uniformBuffer.bindToEffect(effect, "Material");
  31197. this.bindViewProjection(effect);
  31198. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31199. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  31200. // Fresnel
  31201. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  31202. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  31203. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  31204. }
  31205. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  31206. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  31207. }
  31208. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  31209. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  31210. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  31211. }
  31212. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  31213. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  31214. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  31215. }
  31216. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  31217. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  31218. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  31219. }
  31220. }
  31221. // Textures
  31222. if (scene.texturesEnabled) {
  31223. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31224. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  31225. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  31226. }
  31227. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31228. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  31229. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31230. }
  31231. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31232. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31233. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31234. }
  31235. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31236. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  31237. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  31238. }
  31239. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31240. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31241. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31242. }
  31243. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31244. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31245. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31246. }
  31247. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31248. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  31249. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  31250. }
  31251. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31252. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  31253. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31254. if (scene._mirroredCameraPosition) {
  31255. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 0 : 1.0, this.invertNormalMapX ? 1.0 : -1.0, this.invertNormalMapY ? 0 : 1.0, this.invertNormalMapY ? 1.0 : -1.0);
  31256. }
  31257. else {
  31258. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 1.0 : 0, this.invertNormalMapX ? -1.0 : 1.0, this.invertNormalMapY ? 1.0 : 0, this.invertNormalMapY ? -1.0 : 1.0);
  31259. }
  31260. }
  31261. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31262. var depth = 1.0;
  31263. if (!this._refractionTexture.isCube) {
  31264. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  31265. if (this._refractionTexture.depth) {
  31266. depth = this._refractionTexture.depth;
  31267. }
  31268. }
  31269. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  31270. }
  31271. }
  31272. // Point size
  31273. if (this.pointsCloud) {
  31274. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31275. }
  31276. if (defines.SPECULARTERM) {
  31277. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  31278. }
  31279. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  31280. // Diffuse
  31281. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  31282. }
  31283. // Textures
  31284. if (scene.texturesEnabled) {
  31285. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31286. effect.setTexture("diffuseSampler", this._diffuseTexture);
  31287. }
  31288. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31289. effect.setTexture("ambientSampler", this._ambientTexture);
  31290. }
  31291. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31292. effect.setTexture("opacitySampler", this._opacityTexture);
  31293. }
  31294. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31295. if (this._reflectionTexture.isCube) {
  31296. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  31297. }
  31298. else {
  31299. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  31300. }
  31301. }
  31302. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31303. effect.setTexture("emissiveSampler", this._emissiveTexture);
  31304. }
  31305. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31306. effect.setTexture("lightmapSampler", this._lightmapTexture);
  31307. }
  31308. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31309. effect.setTexture("specularSampler", this._specularTexture);
  31310. }
  31311. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31312. effect.setTexture("bumpSampler", this._bumpTexture);
  31313. }
  31314. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31315. var depth = 1.0;
  31316. if (this._refractionTexture.isCube) {
  31317. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  31318. }
  31319. else {
  31320. effect.setTexture("refraction2DSampler", this._refractionTexture);
  31321. }
  31322. }
  31323. }
  31324. // Clip plane
  31325. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  31326. // Colors
  31327. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  31328. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  31329. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31330. }
  31331. if (mustRebind || !this.isFrozen) {
  31332. // Lights
  31333. if (scene.lightsEnabled && !this._disableLighting) {
  31334. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  31335. }
  31336. // View
  31337. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  31338. this.bindView(effect);
  31339. }
  31340. // Fog
  31341. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  31342. // Morph targets
  31343. if (defines.NUM_MORPH_INFLUENCERS) {
  31344. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  31345. }
  31346. // Log. depth
  31347. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  31348. // image processing
  31349. this._imageProcessingConfiguration.bind(this._activeEffect);
  31350. }
  31351. this._uniformBuffer.update();
  31352. this._afterBind(mesh, this._activeEffect);
  31353. };
  31354. StandardMaterial.prototype.getAnimatables = function () {
  31355. var results = [];
  31356. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  31357. results.push(this._diffuseTexture);
  31358. }
  31359. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31360. results.push(this._ambientTexture);
  31361. }
  31362. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31363. results.push(this._opacityTexture);
  31364. }
  31365. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31366. results.push(this._reflectionTexture);
  31367. }
  31368. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31369. results.push(this._emissiveTexture);
  31370. }
  31371. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  31372. results.push(this._specularTexture);
  31373. }
  31374. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31375. results.push(this._bumpTexture);
  31376. }
  31377. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31378. results.push(this._lightmapTexture);
  31379. }
  31380. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31381. results.push(this._refractionTexture);
  31382. }
  31383. return results;
  31384. };
  31385. StandardMaterial.prototype.getActiveTextures = function () {
  31386. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31387. if (this._diffuseTexture) {
  31388. activeTextures.push(this._diffuseTexture);
  31389. }
  31390. if (this._ambientTexture) {
  31391. activeTextures.push(this._ambientTexture);
  31392. }
  31393. if (this._opacityTexture) {
  31394. activeTextures.push(this._opacityTexture);
  31395. }
  31396. if (this._reflectionTexture) {
  31397. activeTextures.push(this._reflectionTexture);
  31398. }
  31399. if (this._emissiveTexture) {
  31400. activeTextures.push(this._emissiveTexture);
  31401. }
  31402. if (this._specularTexture) {
  31403. activeTextures.push(this._specularTexture);
  31404. }
  31405. if (this._bumpTexture) {
  31406. activeTextures.push(this._bumpTexture);
  31407. }
  31408. if (this._lightmapTexture) {
  31409. activeTextures.push(this._lightmapTexture);
  31410. }
  31411. if (this._refractionTexture) {
  31412. activeTextures.push(this._refractionTexture);
  31413. }
  31414. return activeTextures;
  31415. };
  31416. StandardMaterial.prototype.hasTexture = function (texture) {
  31417. if (_super.prototype.hasTexture.call(this, texture)) {
  31418. return true;
  31419. }
  31420. if (this._diffuseTexture === texture) {
  31421. return true;
  31422. }
  31423. if (this._ambientTexture === texture) {
  31424. return true;
  31425. }
  31426. if (this._opacityTexture === texture) {
  31427. return true;
  31428. }
  31429. if (this._reflectionTexture === texture) {
  31430. return true;
  31431. }
  31432. if (this._emissiveTexture === texture) {
  31433. return true;
  31434. }
  31435. if (this._specularTexture === texture) {
  31436. return true;
  31437. }
  31438. if (this._bumpTexture === texture) {
  31439. return true;
  31440. }
  31441. if (this._lightmapTexture === texture) {
  31442. return true;
  31443. }
  31444. if (this._refractionTexture === texture) {
  31445. return true;
  31446. }
  31447. return false;
  31448. };
  31449. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31450. if (forceDisposeTextures) {
  31451. if (this._diffuseTexture) {
  31452. this._diffuseTexture.dispose();
  31453. }
  31454. if (this._ambientTexture) {
  31455. this._ambientTexture.dispose();
  31456. }
  31457. if (this._opacityTexture) {
  31458. this._opacityTexture.dispose();
  31459. }
  31460. if (this._reflectionTexture) {
  31461. this._reflectionTexture.dispose();
  31462. }
  31463. if (this._emissiveTexture) {
  31464. this._emissiveTexture.dispose();
  31465. }
  31466. if (this._specularTexture) {
  31467. this._specularTexture.dispose();
  31468. }
  31469. if (this._bumpTexture) {
  31470. this._bumpTexture.dispose();
  31471. }
  31472. if (this._lightmapTexture) {
  31473. this._lightmapTexture.dispose();
  31474. }
  31475. if (this._refractionTexture) {
  31476. this._refractionTexture.dispose();
  31477. }
  31478. }
  31479. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31480. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31481. }
  31482. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31483. };
  31484. StandardMaterial.prototype.clone = function (name) {
  31485. var _this = this;
  31486. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31487. result.name = name;
  31488. result.id = name;
  31489. return result;
  31490. };
  31491. StandardMaterial.prototype.serialize = function () {
  31492. return BABYLON.SerializationHelper.Serialize(this);
  31493. };
  31494. // Statics
  31495. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31496. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31497. };
  31498. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31499. get: function () {
  31500. return StandardMaterial._DiffuseTextureEnabled;
  31501. },
  31502. set: function (value) {
  31503. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31504. return;
  31505. }
  31506. StandardMaterial._DiffuseTextureEnabled = value;
  31507. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31508. },
  31509. enumerable: true,
  31510. configurable: true
  31511. });
  31512. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31513. get: function () {
  31514. return StandardMaterial._AmbientTextureEnabled;
  31515. },
  31516. set: function (value) {
  31517. if (StandardMaterial._AmbientTextureEnabled === value) {
  31518. return;
  31519. }
  31520. StandardMaterial._AmbientTextureEnabled = value;
  31521. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31522. },
  31523. enumerable: true,
  31524. configurable: true
  31525. });
  31526. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31527. get: function () {
  31528. return StandardMaterial._OpacityTextureEnabled;
  31529. },
  31530. set: function (value) {
  31531. if (StandardMaterial._OpacityTextureEnabled === value) {
  31532. return;
  31533. }
  31534. StandardMaterial._OpacityTextureEnabled = value;
  31535. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31536. },
  31537. enumerable: true,
  31538. configurable: true
  31539. });
  31540. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31541. get: function () {
  31542. return StandardMaterial._ReflectionTextureEnabled;
  31543. },
  31544. set: function (value) {
  31545. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31546. return;
  31547. }
  31548. StandardMaterial._ReflectionTextureEnabled = value;
  31549. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31550. },
  31551. enumerable: true,
  31552. configurable: true
  31553. });
  31554. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31555. get: function () {
  31556. return StandardMaterial._EmissiveTextureEnabled;
  31557. },
  31558. set: function (value) {
  31559. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31560. return;
  31561. }
  31562. StandardMaterial._EmissiveTextureEnabled = value;
  31563. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31564. },
  31565. enumerable: true,
  31566. configurable: true
  31567. });
  31568. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31569. get: function () {
  31570. return StandardMaterial._SpecularTextureEnabled;
  31571. },
  31572. set: function (value) {
  31573. if (StandardMaterial._SpecularTextureEnabled === value) {
  31574. return;
  31575. }
  31576. StandardMaterial._SpecularTextureEnabled = value;
  31577. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31578. },
  31579. enumerable: true,
  31580. configurable: true
  31581. });
  31582. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31583. get: function () {
  31584. return StandardMaterial._BumpTextureEnabled;
  31585. },
  31586. set: function (value) {
  31587. if (StandardMaterial._BumpTextureEnabled === value) {
  31588. return;
  31589. }
  31590. StandardMaterial._BumpTextureEnabled = value;
  31591. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31597. get: function () {
  31598. return StandardMaterial._LightmapTextureEnabled;
  31599. },
  31600. set: function (value) {
  31601. if (StandardMaterial._LightmapTextureEnabled === value) {
  31602. return;
  31603. }
  31604. StandardMaterial._LightmapTextureEnabled = value;
  31605. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31606. },
  31607. enumerable: true,
  31608. configurable: true
  31609. });
  31610. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31611. get: function () {
  31612. return StandardMaterial._RefractionTextureEnabled;
  31613. },
  31614. set: function (value) {
  31615. if (StandardMaterial._RefractionTextureEnabled === value) {
  31616. return;
  31617. }
  31618. StandardMaterial._RefractionTextureEnabled = value;
  31619. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31620. },
  31621. enumerable: true,
  31622. configurable: true
  31623. });
  31624. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31625. get: function () {
  31626. return StandardMaterial._ColorGradingTextureEnabled;
  31627. },
  31628. set: function (value) {
  31629. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31630. return;
  31631. }
  31632. StandardMaterial._ColorGradingTextureEnabled = value;
  31633. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31634. },
  31635. enumerable: true,
  31636. configurable: true
  31637. });
  31638. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31639. get: function () {
  31640. return StandardMaterial._FresnelEnabled;
  31641. },
  31642. set: function (value) {
  31643. if (StandardMaterial._FresnelEnabled === value) {
  31644. return;
  31645. }
  31646. StandardMaterial._FresnelEnabled = value;
  31647. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31648. },
  31649. enumerable: true,
  31650. configurable: true
  31651. });
  31652. // Flags used to enable or disable a type of texture for all Standard Materials
  31653. StandardMaterial._DiffuseTextureEnabled = true;
  31654. StandardMaterial._AmbientTextureEnabled = true;
  31655. StandardMaterial._OpacityTextureEnabled = true;
  31656. StandardMaterial._ReflectionTextureEnabled = true;
  31657. StandardMaterial._EmissiveTextureEnabled = true;
  31658. StandardMaterial._SpecularTextureEnabled = true;
  31659. StandardMaterial._BumpTextureEnabled = true;
  31660. StandardMaterial._LightmapTextureEnabled = true;
  31661. StandardMaterial._RefractionTextureEnabled = true;
  31662. StandardMaterial._ColorGradingTextureEnabled = true;
  31663. StandardMaterial._FresnelEnabled = true;
  31664. __decorate([
  31665. BABYLON.serializeAsTexture("diffuseTexture")
  31666. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31667. __decorate([
  31668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31669. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31670. __decorate([
  31671. BABYLON.serializeAsTexture("ambientTexture")
  31672. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31673. __decorate([
  31674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31675. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31676. __decorate([
  31677. BABYLON.serializeAsTexture("opacityTexture")
  31678. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31679. __decorate([
  31680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31681. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31682. __decorate([
  31683. BABYLON.serializeAsTexture("reflectionTexture")
  31684. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31685. __decorate([
  31686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31687. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31688. __decorate([
  31689. BABYLON.serializeAsTexture("emissiveTexture")
  31690. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31691. __decorate([
  31692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31693. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31694. __decorate([
  31695. BABYLON.serializeAsTexture("specularTexture")
  31696. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31697. __decorate([
  31698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31699. ], StandardMaterial.prototype, "specularTexture", void 0);
  31700. __decorate([
  31701. BABYLON.serializeAsTexture("bumpTexture")
  31702. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31703. __decorate([
  31704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31705. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31706. __decorate([
  31707. BABYLON.serializeAsTexture("lightmapTexture")
  31708. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31709. __decorate([
  31710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31711. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31712. __decorate([
  31713. BABYLON.serializeAsTexture("refractionTexture")
  31714. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31715. __decorate([
  31716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31717. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31718. __decorate([
  31719. BABYLON.serializeAsColor3("ambient")
  31720. ], StandardMaterial.prototype, "ambientColor", void 0);
  31721. __decorate([
  31722. BABYLON.serializeAsColor3("diffuse")
  31723. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31724. __decorate([
  31725. BABYLON.serializeAsColor3("specular")
  31726. ], StandardMaterial.prototype, "specularColor", void 0);
  31727. __decorate([
  31728. BABYLON.serializeAsColor3("emissive")
  31729. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31730. __decorate([
  31731. BABYLON.serialize()
  31732. ], StandardMaterial.prototype, "specularPower", void 0);
  31733. __decorate([
  31734. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31735. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31736. __decorate([
  31737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31738. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31739. __decorate([
  31740. BABYLON.serialize("useEmissiveAsIllumination")
  31741. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31742. __decorate([
  31743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31744. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31745. __decorate([
  31746. BABYLON.serialize("linkEmissiveWithDiffuse")
  31747. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31748. __decorate([
  31749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31750. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31751. __decorate([
  31752. BABYLON.serialize("useSpecularOverAlpha")
  31753. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31754. __decorate([
  31755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31756. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31757. __decorate([
  31758. BABYLON.serialize("useReflectionOverAlpha")
  31759. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31760. __decorate([
  31761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31762. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31763. __decorate([
  31764. BABYLON.serialize("disableLighting")
  31765. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31766. __decorate([
  31767. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31768. ], StandardMaterial.prototype, "disableLighting", void 0);
  31769. __decorate([
  31770. BABYLON.serialize("useParallax")
  31771. ], StandardMaterial.prototype, "_useParallax", void 0);
  31772. __decorate([
  31773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31774. ], StandardMaterial.prototype, "useParallax", void 0);
  31775. __decorate([
  31776. BABYLON.serialize("useParallaxOcclusion")
  31777. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31778. __decorate([
  31779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31780. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31781. __decorate([
  31782. BABYLON.serialize()
  31783. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31784. __decorate([
  31785. BABYLON.serialize("roughness")
  31786. ], StandardMaterial.prototype, "_roughness", void 0);
  31787. __decorate([
  31788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31789. ], StandardMaterial.prototype, "roughness", void 0);
  31790. __decorate([
  31791. BABYLON.serialize()
  31792. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  31793. __decorate([
  31794. BABYLON.serialize()
  31795. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  31796. __decorate([
  31797. BABYLON.serialize("useLightmapAsShadowmap")
  31798. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  31799. __decorate([
  31800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31801. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31802. __decorate([
  31803. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  31804. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  31805. __decorate([
  31806. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31807. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  31808. __decorate([
  31809. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  31810. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  31811. __decorate([
  31812. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31813. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  31814. __decorate([
  31815. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  31816. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  31817. __decorate([
  31818. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31819. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  31820. __decorate([
  31821. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  31822. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  31823. __decorate([
  31824. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31825. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  31826. __decorate([
  31827. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  31828. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  31829. __decorate([
  31830. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31831. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  31832. __decorate([
  31833. BABYLON.serialize("useReflectionFresnelFromSpecular")
  31834. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  31835. __decorate([
  31836. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31837. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  31838. __decorate([
  31839. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  31840. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  31841. __decorate([
  31842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31843. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  31844. __decorate([
  31845. BABYLON.serialize("maxSimultaneousLights")
  31846. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  31847. __decorate([
  31848. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31849. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  31850. __decorate([
  31851. BABYLON.serialize("invertNormalMapX")
  31852. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  31853. __decorate([
  31854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31855. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  31856. __decorate([
  31857. BABYLON.serialize("invertNormalMapY")
  31858. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  31859. __decorate([
  31860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31861. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  31862. __decorate([
  31863. BABYLON.serialize("twoSidedLighting")
  31864. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  31865. __decorate([
  31866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31867. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  31868. __decorate([
  31869. BABYLON.serialize()
  31870. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  31871. return StandardMaterial;
  31872. }(BABYLON.PushMaterial));
  31873. BABYLON.StandardMaterial = StandardMaterial;
  31874. })(BABYLON || (BABYLON = {}));
  31875. //# sourceMappingURL=babylon.standardMaterial.js.map
  31876. var BABYLON;
  31877. (function (BABYLON) {
  31878. var PBRMaterialDefines = (function (_super) {
  31879. __extends(PBRMaterialDefines, _super);
  31880. function PBRMaterialDefines() {
  31881. var _this = _super.call(this) || this;
  31882. _this.PBR = true;
  31883. _this.MAINUV1 = false;
  31884. _this.MAINUV2 = false;
  31885. _this.UV1 = false;
  31886. _this.UV2 = false;
  31887. _this.ALBEDO = false;
  31888. _this.ALBEDODIRECTUV = 0;
  31889. _this.VERTEXCOLOR = false;
  31890. _this.AMBIENT = false;
  31891. _this.AMBIENTDIRECTUV = 0;
  31892. _this.AMBIENTINGRAYSCALE = false;
  31893. _this.OPACITY = false;
  31894. _this.VERTEXALPHA = false;
  31895. _this.OPACITYDIRECTUV = 0;
  31896. _this.OPACITYRGB = false;
  31897. _this.ALPHATEST = false;
  31898. _this.DEPTHPREPASS = false;
  31899. _this.ALPHABLEND = false;
  31900. _this.ALPHAFROMALBEDO = false;
  31901. _this.ALPHATESTVALUE = 0.5;
  31902. _this.SPECULAROVERALPHA = false;
  31903. _this.RADIANCEOVERALPHA = false;
  31904. _this.ALPHAFRESNEL = false;
  31905. _this.PREMULTIPLYALPHA = false;
  31906. _this.EMISSIVE = false;
  31907. _this.EMISSIVEDIRECTUV = 0;
  31908. _this.REFLECTIVITY = false;
  31909. _this.REFLECTIVITYDIRECTUV = 0;
  31910. _this.SPECULARTERM = false;
  31911. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  31912. _this.MICROSURFACEAUTOMATIC = false;
  31913. _this.LODBASEDMICROSFURACE = false;
  31914. _this.MICROSURFACEMAP = false;
  31915. _this.MICROSURFACEMAPDIRECTUV = 0;
  31916. _this.METALLICWORKFLOW = false;
  31917. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  31918. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  31919. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  31920. _this.AOSTOREINMETALMAPRED = false;
  31921. _this.ENVIRONMENTBRDF = false;
  31922. _this.NORMAL = false;
  31923. _this.TANGENT = false;
  31924. _this.BUMP = false;
  31925. _this.BUMPDIRECTUV = 0;
  31926. _this.PARALLAX = false;
  31927. _this.PARALLAXOCCLUSION = false;
  31928. _this.NORMALXYSCALE = true;
  31929. _this.LIGHTMAP = false;
  31930. _this.LIGHTMAPDIRECTUV = 0;
  31931. _this.USELIGHTMAPASSHADOWMAP = false;
  31932. _this.REFLECTION = false;
  31933. _this.REFLECTIONMAP_3D = false;
  31934. _this.REFLECTIONMAP_SPHERICAL = false;
  31935. _this.REFLECTIONMAP_PLANAR = false;
  31936. _this.REFLECTIONMAP_CUBIC = false;
  31937. _this.REFLECTIONMAP_PROJECTION = false;
  31938. _this.REFLECTIONMAP_SKYBOX = false;
  31939. _this.REFLECTIONMAP_EXPLICIT = false;
  31940. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31941. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31942. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31943. _this.INVERTCUBICMAP = false;
  31944. _this.USESPHERICALFROMREFLECTIONMAP = false;
  31945. _this.USESPHERICALINFRAGMENT = false;
  31946. _this.REFLECTIONMAP_OPPOSITEZ = false;
  31947. _this.LODINREFLECTIONALPHA = false;
  31948. _this.GAMMAREFLECTION = false;
  31949. _this.REFRACTION = false;
  31950. _this.REFRACTIONMAP_3D = false;
  31951. _this.REFRACTIONMAP_OPPOSITEZ = false;
  31952. _this.LODINREFRACTIONALPHA = false;
  31953. _this.GAMMAREFRACTION = false;
  31954. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  31955. _this.INSTANCES = false;
  31956. _this.NUM_BONE_INFLUENCERS = 0;
  31957. _this.BonesPerMesh = 0;
  31958. _this.MORPHTARGETS = false;
  31959. _this.MORPHTARGETS_NORMAL = false;
  31960. _this.MORPHTARGETS_TANGENT = false;
  31961. _this.NUM_MORPH_INFLUENCERS = 0;
  31962. _this.IMAGEPROCESSING = false;
  31963. _this.VIGNETTE = false;
  31964. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  31965. _this.VIGNETTEBLENDMODEOPAQUE = false;
  31966. _this.TONEMAPPING = false;
  31967. _this.CONTRAST = false;
  31968. _this.COLORCURVES = false;
  31969. _this.COLORGRADING = false;
  31970. _this.SAMPLER3DGREENDEPTH = false;
  31971. _this.SAMPLER3DBGRMAP = false;
  31972. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  31973. _this.EXPOSURE = false;
  31974. _this.USEPHYSICALLIGHTFALLOFF = false;
  31975. _this.TWOSIDEDLIGHTING = false;
  31976. _this.SHADOWFLOAT = false;
  31977. _this.USERIGHTHANDEDSYSTEM = false;
  31978. _this.CLIPPLANE = false;
  31979. _this.POINTSIZE = false;
  31980. _this.FOG = false;
  31981. _this.LOGARITHMICDEPTH = false;
  31982. _this.FORCENORMALFORWARD = false;
  31983. _this.rebuild();
  31984. return _this;
  31985. }
  31986. PBRMaterialDefines.prototype.reset = function () {
  31987. _super.prototype.reset.call(this);
  31988. this.ALPHATESTVALUE = 0.5;
  31989. this.PBR = true;
  31990. };
  31991. return PBRMaterialDefines;
  31992. }(BABYLON.MaterialDefines));
  31993. /**
  31994. * The Physically based material base class of BJS.
  31995. *
  31996. * This offers the main features of a standard PBR material.
  31997. * For more information, please refer to the documentation :
  31998. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31999. */
  32000. var PBRBaseMaterial = (function (_super) {
  32001. __extends(PBRBaseMaterial, _super);
  32002. /**
  32003. * Instantiates a new PBRMaterial instance.
  32004. *
  32005. * @param name The material name
  32006. * @param scene The scene the material will be use in.
  32007. */
  32008. function PBRBaseMaterial(name, scene) {
  32009. var _this = _super.call(this, name, scene) || this;
  32010. /**
  32011. * Intensity of the direct lights e.g. the four lights available in your scene.
  32012. * This impacts both the direct diffuse and specular highlights.
  32013. */
  32014. _this._directIntensity = 1.0;
  32015. /**
  32016. * Intensity of the emissive part of the material.
  32017. * This helps controlling the emissive effect without modifying the emissive color.
  32018. */
  32019. _this._emissiveIntensity = 1.0;
  32020. /**
  32021. * Intensity of the environment e.g. how much the environment will light the object
  32022. * either through harmonics for rough material or through the refelction for shiny ones.
  32023. */
  32024. _this._environmentIntensity = 1.0;
  32025. /**
  32026. * This is a special control allowing the reduction of the specular highlights coming from the
  32027. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32028. */
  32029. _this._specularIntensity = 1.0;
  32030. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  32031. /**
  32032. * Debug Control allowing disabling the bump map on this material.
  32033. */
  32034. _this._disableBumpMap = false;
  32035. /**
  32036. * AKA Occlusion Texture Intensity in other nomenclature.
  32037. */
  32038. _this._ambientTextureStrength = 1.0;
  32039. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  32040. /**
  32041. * AKA Diffuse Color in other nomenclature.
  32042. */
  32043. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  32044. /**
  32045. * AKA Specular Color in other nomenclature.
  32046. */
  32047. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32048. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  32049. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  32050. /**
  32051. * AKA Glossiness in other nomenclature.
  32052. */
  32053. _this._microSurface = 0.9;
  32054. /**
  32055. * source material index of refraction (IOR)' / 'destination material IOR.
  32056. */
  32057. _this._indexOfRefraction = 0.66;
  32058. /**
  32059. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32060. */
  32061. _this._invertRefractionY = false;
  32062. /**
  32063. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32064. * Materials half opaque for instance using refraction could benefit from this control.
  32065. */
  32066. _this._linkRefractionWithTransparency = false;
  32067. _this._useLightmapAsShadowmap = false;
  32068. /**
  32069. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32070. */
  32071. _this._useAlphaFromAlbedoTexture = false;
  32072. /**
  32073. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32074. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32075. */
  32076. _this._useSpecularOverAlpha = true;
  32077. /**
  32078. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32079. */
  32080. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  32081. /**
  32082. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32083. */
  32084. _this._useRoughnessFromMetallicTextureAlpha = true;
  32085. /**
  32086. * Specifies if the metallic texture contains the roughness information in its green channel.
  32087. */
  32088. _this._useRoughnessFromMetallicTextureGreen = false;
  32089. /**
  32090. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32091. */
  32092. _this._useMetallnessFromMetallicTextureBlue = false;
  32093. /**
  32094. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32095. */
  32096. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  32097. /**
  32098. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32099. */
  32100. _this._useAmbientInGrayScale = false;
  32101. /**
  32102. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32103. * The material will try to infer what glossiness each pixel should be.
  32104. */
  32105. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  32106. /**
  32107. * BJS is using an harcoded light falloff based on a manually sets up range.
  32108. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32109. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32110. */
  32111. _this._usePhysicalLightFalloff = true;
  32112. /**
  32113. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32114. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32115. */
  32116. _this._useRadianceOverAlpha = true;
  32117. /**
  32118. * Allows using the bump map in parallax mode.
  32119. */
  32120. _this._useParallax = false;
  32121. /**
  32122. * Allows using the bump map in parallax occlusion mode.
  32123. */
  32124. _this._useParallaxOcclusion = false;
  32125. /**
  32126. * Controls the scale bias of the parallax mode.
  32127. */
  32128. _this._parallaxScaleBias = 0.05;
  32129. /**
  32130. * If sets to true, disables all the lights affecting the material.
  32131. */
  32132. _this._disableLighting = false;
  32133. /**
  32134. * Number of Simultaneous lights allowed on the material.
  32135. */
  32136. _this._maxSimultaneousLights = 4;
  32137. /**
  32138. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  32139. */
  32140. _this._invertNormalMapX = false;
  32141. /**
  32142. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  32143. */
  32144. _this._invertNormalMapY = false;
  32145. /**
  32146. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32147. */
  32148. _this._twoSidedLighting = false;
  32149. /**
  32150. * Defines the alpha limits in alpha test mode.
  32151. */
  32152. _this._alphaCutOff = 0.4;
  32153. /**
  32154. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32155. */
  32156. _this._forceAlphaTest = false;
  32157. /**
  32158. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32159. * in your scene composition.
  32160. */
  32161. _this._preMultiplyAlpha = false;
  32162. /**
  32163. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32164. * And/Or occlude the blended part.
  32165. */
  32166. _this._useAlphaFresnel = false;
  32167. /**
  32168. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  32169. * from cos thetav and roughness:
  32170. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  32171. */
  32172. _this._environmentBRDFTexture = null;
  32173. /**
  32174. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32175. */
  32176. _this._forceIrradianceInFragment = false;
  32177. /**
  32178. * Force normal to face away from face.
  32179. * (Temporary internal fix to remove before 3.1)
  32180. */
  32181. _this._forceNormalForward = false;
  32182. _this._renderTargets = new BABYLON.SmartArray(16);
  32183. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32184. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32185. _this._tempColor = new BABYLON.Color3();
  32186. // Setup the default processing configuration to the scene.
  32187. _this._attachImageProcessingConfiguration(null);
  32188. _this.getRenderTargetTextures = function () {
  32189. _this._renderTargets.reset();
  32190. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32191. _this._renderTargets.push(_this._reflectionTexture);
  32192. }
  32193. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32194. _this._renderTargets.push(_this._refractionTexture);
  32195. }
  32196. return _this._renderTargets;
  32197. };
  32198. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32199. return _this;
  32200. }
  32201. /**
  32202. * Attaches a new image processing configuration to the PBR Material.
  32203. * @param configuration
  32204. */
  32205. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32206. var _this = this;
  32207. if (configuration === this._imageProcessingConfiguration) {
  32208. return;
  32209. }
  32210. // Detaches observer.
  32211. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32212. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32213. }
  32214. // Pick the scene configuration if needed.
  32215. if (!configuration) {
  32216. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32217. }
  32218. else {
  32219. this._imageProcessingConfiguration = configuration;
  32220. }
  32221. // Attaches observer.
  32222. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32223. _this._markAllSubMeshesAsImageProcessingDirty();
  32224. });
  32225. };
  32226. PBRBaseMaterial.prototype.getClassName = function () {
  32227. return "PBRBaseMaterial";
  32228. };
  32229. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  32230. get: function () {
  32231. return this._useLogarithmicDepth;
  32232. },
  32233. set: function (value) {
  32234. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32235. },
  32236. enumerable: true,
  32237. configurable: true
  32238. });
  32239. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  32240. if (this._linkRefractionWithTransparency) {
  32241. return false;
  32242. }
  32243. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  32244. };
  32245. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  32246. if (this._forceAlphaTest) {
  32247. return true;
  32248. }
  32249. if (this._linkRefractionWithTransparency) {
  32250. return false;
  32251. }
  32252. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  32253. };
  32254. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32255. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  32256. };
  32257. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  32258. return this._albedoTexture;
  32259. };
  32260. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32261. if (this.isFrozen) {
  32262. if (this._wasPreviouslyReady) {
  32263. return true;
  32264. }
  32265. }
  32266. if (!subMesh._materialDefines) {
  32267. subMesh._materialDefines = new PBRMaterialDefines();
  32268. }
  32269. var scene = this.getScene();
  32270. var defines = subMesh._materialDefines;
  32271. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32272. if (defines._renderId === scene.getRenderId()) {
  32273. return true;
  32274. }
  32275. }
  32276. var engine = scene.getEngine();
  32277. // Lights
  32278. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32279. defines._needNormals = true;
  32280. // Textures
  32281. if (defines._areTexturesDirty) {
  32282. defines._needUVs = false;
  32283. if (scene.texturesEnabled) {
  32284. if (scene.getEngine().getCaps().textureLOD) {
  32285. defines.LODBASEDMICROSFURACE = true;
  32286. }
  32287. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32288. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  32289. return false;
  32290. }
  32291. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  32292. }
  32293. else {
  32294. defines.ALBEDO = false;
  32295. }
  32296. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32297. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32298. return false;
  32299. }
  32300. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32301. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  32302. }
  32303. else {
  32304. defines.AMBIENT = false;
  32305. }
  32306. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32307. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32308. return false;
  32309. }
  32310. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32311. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32312. }
  32313. else {
  32314. defines.OPACITY = false;
  32315. }
  32316. var reflectionTexture = this._getReflectionTexture();
  32317. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32318. if (!reflectionTexture.isReadyOrNotBlocking()) {
  32319. return false;
  32320. }
  32321. defines.REFLECTION = true;
  32322. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  32323. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  32324. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32325. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  32326. defines.INVERTCUBICMAP = true;
  32327. }
  32328. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  32329. switch (reflectionTexture.coordinatesMode) {
  32330. case BABYLON.Texture.CUBIC_MODE:
  32331. case BABYLON.Texture.INVCUBIC_MODE:
  32332. defines.REFLECTIONMAP_CUBIC = true;
  32333. break;
  32334. case BABYLON.Texture.EXPLICIT_MODE:
  32335. defines.REFLECTIONMAP_EXPLICIT = true;
  32336. break;
  32337. case BABYLON.Texture.PLANAR_MODE:
  32338. defines.REFLECTIONMAP_PLANAR = true;
  32339. break;
  32340. case BABYLON.Texture.PROJECTION_MODE:
  32341. defines.REFLECTIONMAP_PROJECTION = true;
  32342. break;
  32343. case BABYLON.Texture.SKYBOX_MODE:
  32344. defines.REFLECTIONMAP_SKYBOX = true;
  32345. break;
  32346. case BABYLON.Texture.SPHERICAL_MODE:
  32347. defines.REFLECTIONMAP_SPHERICAL = true;
  32348. break;
  32349. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  32350. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  32351. break;
  32352. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  32353. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  32354. break;
  32355. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  32356. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  32357. break;
  32358. }
  32359. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  32360. if (reflectionTexture.sphericalPolynomial) {
  32361. defines.USESPHERICALFROMREFLECTIONMAP = true;
  32362. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  32363. defines.USESPHERICALINFRAGMENT = true;
  32364. }
  32365. }
  32366. }
  32367. }
  32368. else {
  32369. defines.REFLECTION = false;
  32370. defines.REFLECTIONMAP_3D = false;
  32371. defines.REFLECTIONMAP_SPHERICAL = false;
  32372. defines.REFLECTIONMAP_PLANAR = false;
  32373. defines.REFLECTIONMAP_CUBIC = false;
  32374. defines.REFLECTIONMAP_PROJECTION = false;
  32375. defines.REFLECTIONMAP_SKYBOX = false;
  32376. defines.REFLECTIONMAP_EXPLICIT = false;
  32377. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32378. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32379. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32380. defines.INVERTCUBICMAP = false;
  32381. defines.USESPHERICALFROMREFLECTIONMAP = false;
  32382. defines.USESPHERICALINFRAGMENT = false;
  32383. defines.REFLECTIONMAP_OPPOSITEZ = false;
  32384. defines.LODINREFLECTIONALPHA = false;
  32385. defines.GAMMAREFLECTION = false;
  32386. }
  32387. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32388. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  32389. return false;
  32390. }
  32391. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  32392. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  32393. }
  32394. else {
  32395. defines.LIGHTMAP = false;
  32396. }
  32397. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32398. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  32399. return false;
  32400. }
  32401. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  32402. }
  32403. else {
  32404. defines.EMISSIVE = false;
  32405. }
  32406. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32407. if (this._metallicTexture) {
  32408. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  32409. return false;
  32410. }
  32411. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  32412. defines.METALLICWORKFLOW = true;
  32413. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  32414. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  32415. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  32416. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  32417. }
  32418. else if (this._reflectivityTexture) {
  32419. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  32420. return false;
  32421. }
  32422. defines.METALLICWORKFLOW = false;
  32423. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  32424. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  32425. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  32426. }
  32427. else {
  32428. defines.METALLICWORKFLOW = false;
  32429. defines.REFLECTIVITY = false;
  32430. }
  32431. if (this._microSurfaceTexture) {
  32432. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  32433. return false;
  32434. }
  32435. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  32436. }
  32437. else {
  32438. defines.MICROSURFACEMAP = false;
  32439. }
  32440. }
  32441. else {
  32442. defines.REFLECTIVITY = false;
  32443. defines.MICROSURFACEMAP = false;
  32444. }
  32445. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32446. // Bump texure can not be none blocking.
  32447. if (!this._bumpTexture.isReady()) {
  32448. return false;
  32449. }
  32450. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32451. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32452. defines.PARALLAX = true;
  32453. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  32454. }
  32455. else {
  32456. defines.PARALLAX = false;
  32457. }
  32458. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  32459. }
  32460. else {
  32461. defines.BUMP = false;
  32462. }
  32463. var refractionTexture = this._getRefractionTexture();
  32464. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32465. if (!refractionTexture.isReadyOrNotBlocking()) {
  32466. return false;
  32467. }
  32468. defines.REFRACTION = true;
  32469. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  32470. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  32471. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  32472. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32473. if (this._linkRefractionWithTransparency) {
  32474. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  32475. }
  32476. }
  32477. else {
  32478. defines.REFRACTION = false;
  32479. }
  32480. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32481. // This is blocking.
  32482. if (!this._environmentBRDFTexture.isReady()) {
  32483. return false;
  32484. }
  32485. defines.ENVIRONMENTBRDF = true;
  32486. }
  32487. if (this._shouldUseAlphaFromAlbedoTexture()) {
  32488. defines.ALPHAFROMALBEDO = true;
  32489. }
  32490. }
  32491. if (this._useSpecularOverAlpha) {
  32492. defines.SPECULAROVERALPHA = true;
  32493. }
  32494. if (this._usePhysicalLightFalloff) {
  32495. defines.USEPHYSICALLIGHTFALLOFF = true;
  32496. }
  32497. if (this._useRadianceOverAlpha) {
  32498. defines.RADIANCEOVERALPHA = true;
  32499. }
  32500. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  32501. defines.METALLICWORKFLOW = true;
  32502. }
  32503. if (!this.backFaceCulling && this._twoSidedLighting) {
  32504. defines.TWOSIDEDLIGHTING = true;
  32505. }
  32506. defines.ALPHATESTVALUE = this._alphaCutOff;
  32507. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  32508. defines.ALPHABLEND = this.needAlphaBlending();
  32509. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  32510. }
  32511. if (defines._areImageProcessingDirty) {
  32512. if (!this._imageProcessingConfiguration.isReady()) {
  32513. return false;
  32514. }
  32515. this._imageProcessingConfiguration.prepareDefines(defines);
  32516. }
  32517. defines.FORCENORMALFORWARD = this._forceNormalForward;
  32518. // Misc.
  32519. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32520. // Values that need to be evaluated on every frame
  32521. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  32522. // Attribs
  32523. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  32524. if (mesh) {
  32525. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32526. mesh.createNormals(true);
  32527. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  32528. }
  32529. }
  32530. }
  32531. // Get correct effect
  32532. if (defines.isDirty) {
  32533. defines.markAsProcessed();
  32534. scene.resetCachedMaterial();
  32535. // Fallbacks
  32536. var fallbacks = new BABYLON.EffectFallbacks();
  32537. if (defines.ENVIRONMENTBRDF) {
  32538. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  32539. }
  32540. if (defines.REFLECTION) {
  32541. fallbacks.addFallback(0, "REFLECTION");
  32542. }
  32543. if (defines.REFRACTION) {
  32544. fallbacks.addFallback(0, "REFRACTION");
  32545. }
  32546. if (defines.REFLECTIVITY) {
  32547. fallbacks.addFallback(0, "REFLECTIVITY");
  32548. }
  32549. if (defines.BUMP) {
  32550. fallbacks.addFallback(0, "BUMP");
  32551. }
  32552. if (defines.PARALLAX) {
  32553. fallbacks.addFallback(1, "PARALLAX");
  32554. }
  32555. if (defines.PARALLAXOCCLUSION) {
  32556. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32557. }
  32558. if (defines.SPECULAROVERALPHA) {
  32559. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32560. }
  32561. if (defines.FOG) {
  32562. fallbacks.addFallback(1, "FOG");
  32563. }
  32564. if (defines.POINTSIZE) {
  32565. fallbacks.addFallback(0, "POINTSIZE");
  32566. }
  32567. if (defines.LOGARITHMICDEPTH) {
  32568. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32569. }
  32570. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32571. if (defines.SPECULARTERM) {
  32572. fallbacks.addFallback(0, "SPECULARTERM");
  32573. }
  32574. if (defines.NUM_BONE_INFLUENCERS > 0) {
  32575. fallbacks.addCPUSkinningFallback(0, mesh);
  32576. }
  32577. //Attributes
  32578. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32579. if (defines.NORMAL) {
  32580. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32581. }
  32582. if (defines.TANGENT) {
  32583. attribs.push(BABYLON.VertexBuffer.TangentKind);
  32584. }
  32585. if (defines.UV1) {
  32586. attribs.push(BABYLON.VertexBuffer.UVKind);
  32587. }
  32588. if (defines.UV2) {
  32589. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32590. }
  32591. if (defines.VERTEXCOLOR) {
  32592. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32593. }
  32594. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32595. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32596. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32597. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  32598. "vFogInfos", "vFogColor", "pointSize",
  32599. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32600. "mBones",
  32601. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32602. "vLightingIntensity",
  32603. "logarithmicDepthConstant",
  32604. "vSphericalX", "vSphericalY", "vSphericalZ",
  32605. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  32606. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  32607. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  32608. "vNormalReoderParams"
  32609. ];
  32610. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  32611. "bumpSampler", "lightmapSampler", "opacitySampler",
  32612. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  32613. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  32614. "microSurfaceSampler", "environmentBrdfSampler"];
  32615. var uniformBuffers = ["Material", "Scene"];
  32616. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32617. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32618. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32619. uniformsNames: uniforms,
  32620. uniformBuffersNames: uniformBuffers,
  32621. samplers: samplers,
  32622. defines: defines,
  32623. maxSimultaneousLights: this._maxSimultaneousLights
  32624. });
  32625. var onCompiled = function (effect) {
  32626. if (this.onCompiled) {
  32627. this.onCompiled(effect);
  32628. }
  32629. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  32630. }.bind(this);
  32631. var join = defines.toString();
  32632. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  32633. attributes: attribs,
  32634. uniformsNames: uniforms,
  32635. uniformBuffersNames: uniformBuffers,
  32636. samplers: samplers,
  32637. defines: join,
  32638. fallbacks: fallbacks,
  32639. onCompiled: onCompiled,
  32640. onError: this.onError,
  32641. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32642. }, engine), defines);
  32643. this.buildUniformLayout();
  32644. }
  32645. if (!subMesh.effect.isReady()) {
  32646. return false;
  32647. }
  32648. defines._renderId = scene.getRenderId();
  32649. this._wasPreviouslyReady = true;
  32650. return true;
  32651. };
  32652. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  32653. // Order is important !
  32654. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  32655. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  32656. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32657. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32658. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32659. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  32660. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  32661. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32662. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32663. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32664. this._uniformBuffer.addUniform("albedoMatrix", 16);
  32665. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32666. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32667. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32668. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32669. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  32670. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  32671. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32672. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  32673. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32674. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32675. this._uniformBuffer.addUniform("vReflectionColor", 3);
  32676. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  32677. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  32678. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  32679. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  32680. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  32681. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32682. this._uniformBuffer.addUniform("pointSize", 1);
  32683. this._uniformBuffer.create();
  32684. };
  32685. PBRBaseMaterial.prototype.unbind = function () {
  32686. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32687. this._uniformBuffer.setTexture("reflectionSampler", null);
  32688. }
  32689. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32690. this._uniformBuffer.setTexture("refractionSampler", null);
  32691. }
  32692. _super.prototype.unbind.call(this);
  32693. };
  32694. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32695. this._activeEffect.setMatrix("world", world);
  32696. };
  32697. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32698. var scene = this.getScene();
  32699. var defines = subMesh._materialDefines;
  32700. if (!defines) {
  32701. return;
  32702. }
  32703. var effect = subMesh.effect;
  32704. this._activeEffect = effect;
  32705. // Matrices
  32706. this.bindOnlyWorldMatrix(world);
  32707. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32708. // Bones
  32709. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  32710. if (mustRebind) {
  32711. this._uniformBuffer.bindToEffect(effect, "Material");
  32712. this.bindViewProjection(effect);
  32713. var reflectionTexture = this._getReflectionTexture();
  32714. var refractionTexture = this._getRefractionTexture();
  32715. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32716. // Texture uniforms
  32717. if (scene.texturesEnabled) {
  32718. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32719. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  32720. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  32721. }
  32722. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32723. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  32724. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32725. }
  32726. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32727. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32728. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32729. }
  32730. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32731. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  32732. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  32733. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  32734. var polynomials = reflectionTexture.sphericalPolynomial;
  32735. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  32736. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  32737. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  32738. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  32739. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  32740. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  32741. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  32742. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  32743. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  32744. }
  32745. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  32746. }
  32747. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32748. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32749. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32750. }
  32751. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32752. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32753. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32754. }
  32755. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32756. if (this._metallicTexture) {
  32757. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  32758. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  32759. }
  32760. else if (this._reflectivityTexture) {
  32761. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  32762. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  32763. }
  32764. if (this._microSurfaceTexture) {
  32765. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  32766. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  32767. }
  32768. }
  32769. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32770. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  32771. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32772. if (scene._mirroredCameraPosition) {
  32773. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 0 : 1.0, this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 0 : 1.0, this._invertNormalMapY ? 1.0 : -1.0);
  32774. }
  32775. else {
  32776. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 1.0 : 0, this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? 1.0 : 0, this._invertNormalMapY ? -1.0 : 1.0);
  32777. }
  32778. }
  32779. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32780. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  32781. var depth = 1.0;
  32782. if (!refractionTexture.isCube) {
  32783. if (refractionTexture.depth) {
  32784. depth = refractionTexture.depth;
  32785. }
  32786. }
  32787. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  32788. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  32789. }
  32790. }
  32791. // Point size
  32792. if (this.pointsCloud) {
  32793. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32794. }
  32795. // Colors
  32796. if (defines.METALLICWORKFLOW) {
  32797. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  32798. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  32799. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  32800. }
  32801. else {
  32802. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  32803. }
  32804. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  32805. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  32806. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  32807. // Misc
  32808. this._lightingInfos.x = this._directIntensity;
  32809. this._lightingInfos.y = this._emissiveIntensity;
  32810. this._lightingInfos.z = this._environmentIntensity;
  32811. this._lightingInfos.w = this._specularIntensity;
  32812. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  32813. }
  32814. // Textures
  32815. if (scene.texturesEnabled) {
  32816. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32817. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  32818. }
  32819. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32820. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  32821. }
  32822. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32823. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  32824. }
  32825. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32826. if (defines.LODBASEDMICROSFURACE) {
  32827. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  32828. }
  32829. else {
  32830. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  32831. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  32832. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  32833. }
  32834. }
  32835. if (defines.ENVIRONMENTBRDF) {
  32836. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  32837. }
  32838. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32839. if (defines.LODBASEDMICROSFURACE) {
  32840. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  32841. }
  32842. else {
  32843. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  32844. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  32845. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  32846. }
  32847. }
  32848. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32849. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  32850. }
  32851. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32852. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  32853. }
  32854. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32855. if (this._metallicTexture) {
  32856. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  32857. }
  32858. else if (this._reflectivityTexture) {
  32859. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  32860. }
  32861. if (this._microSurfaceTexture) {
  32862. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  32863. }
  32864. }
  32865. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32866. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  32867. }
  32868. }
  32869. // Clip plane
  32870. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  32871. // Colors
  32872. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  32873. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  32874. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  32875. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32876. }
  32877. if (mustRebind || !this.isFrozen) {
  32878. // Lights
  32879. if (scene.lightsEnabled && !this._disableLighting) {
  32880. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  32881. }
  32882. // View
  32883. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  32884. this.bindView(effect);
  32885. }
  32886. // Fog
  32887. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  32888. // Morph targets
  32889. if (defines.NUM_MORPH_INFLUENCERS) {
  32890. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  32891. }
  32892. // image processing
  32893. this._imageProcessingConfiguration.bind(this._activeEffect);
  32894. // Log. depth
  32895. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  32896. }
  32897. this._uniformBuffer.update();
  32898. this._afterBind(mesh);
  32899. scene = null;
  32900. };
  32901. PBRBaseMaterial.prototype.getAnimatables = function () {
  32902. var results = [];
  32903. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  32904. results.push(this._albedoTexture);
  32905. }
  32906. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32907. results.push(this._ambientTexture);
  32908. }
  32909. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32910. results.push(this._opacityTexture);
  32911. }
  32912. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32913. results.push(this._reflectionTexture);
  32914. }
  32915. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32916. results.push(this._emissiveTexture);
  32917. }
  32918. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  32919. results.push(this._metallicTexture);
  32920. }
  32921. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  32922. results.push(this._reflectivityTexture);
  32923. }
  32924. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32925. results.push(this._bumpTexture);
  32926. }
  32927. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32928. results.push(this._lightmapTexture);
  32929. }
  32930. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32931. results.push(this._refractionTexture);
  32932. }
  32933. return results;
  32934. };
  32935. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  32936. if (this._reflectionTexture) {
  32937. return this._reflectionTexture;
  32938. }
  32939. return this.getScene().environmentTexture;
  32940. };
  32941. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  32942. if (this._refractionTexture) {
  32943. return this._refractionTexture;
  32944. }
  32945. if (this._linkRefractionWithTransparency) {
  32946. return this.getScene().environmentTexture;
  32947. }
  32948. return null;
  32949. };
  32950. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32951. if (forceDisposeTextures) {
  32952. if (this._albedoTexture) {
  32953. this._albedoTexture.dispose();
  32954. }
  32955. if (this._ambientTexture) {
  32956. this._ambientTexture.dispose();
  32957. }
  32958. if (this._opacityTexture) {
  32959. this._opacityTexture.dispose();
  32960. }
  32961. if (this._reflectionTexture) {
  32962. this._reflectionTexture.dispose();
  32963. }
  32964. if (this._environmentBRDFTexture) {
  32965. this._environmentBRDFTexture.dispose();
  32966. }
  32967. if (this._emissiveTexture) {
  32968. this._emissiveTexture.dispose();
  32969. }
  32970. if (this._metallicTexture) {
  32971. this._metallicTexture.dispose();
  32972. }
  32973. if (this._reflectivityTexture) {
  32974. this._reflectivityTexture.dispose();
  32975. }
  32976. if (this._bumpTexture) {
  32977. this._bumpTexture.dispose();
  32978. }
  32979. if (this._lightmapTexture) {
  32980. this._lightmapTexture.dispose();
  32981. }
  32982. if (this._refractionTexture) {
  32983. this._refractionTexture.dispose();
  32984. }
  32985. }
  32986. this._renderTargets.dispose();
  32987. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32988. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32989. }
  32990. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32991. };
  32992. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  32993. __decorate([
  32994. BABYLON.serializeAsImageProcessingConfiguration()
  32995. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  32996. __decorate([
  32997. BABYLON.serialize()
  32998. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  32999. return PBRBaseMaterial;
  33000. }(BABYLON.PushMaterial));
  33001. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  33002. })(BABYLON || (BABYLON = {}));
  33003. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  33004. var BABYLON;
  33005. (function (BABYLON) {
  33006. var Internals;
  33007. (function (Internals) {
  33008. /**
  33009. * The Physically based simple base material of BJS.
  33010. *
  33011. * This enables better naming and convention enforcements on top of the pbrMaterial.
  33012. * It is used as the base class for both the specGloss and metalRough conventions.
  33013. */
  33014. var PBRBaseSimpleMaterial = (function (_super) {
  33015. __extends(PBRBaseSimpleMaterial, _super);
  33016. /**
  33017. * Instantiates a new PBRMaterial instance.
  33018. *
  33019. * @param name The material name
  33020. * @param scene The scene the material will be use in.
  33021. */
  33022. function PBRBaseSimpleMaterial(name, scene) {
  33023. var _this = _super.call(this, name, scene) || this;
  33024. /**
  33025. * Number of Simultaneous lights allowed on the material.
  33026. */
  33027. _this.maxSimultaneousLights = 4;
  33028. /**
  33029. * If sets to true, disables all the lights affecting the material.
  33030. */
  33031. _this.disableLighting = false;
  33032. /**
  33033. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33034. */
  33035. _this.invertNormalMapX = false;
  33036. /**
  33037. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33038. */
  33039. _this.invertNormalMapY = false;
  33040. /**
  33041. * Emissivie color used to self-illuminate the model.
  33042. */
  33043. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33044. /**
  33045. * Occlusion Channel Strenght.
  33046. */
  33047. _this.occlusionStrength = 1.0;
  33048. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  33049. _this._useAmbientInGrayScale = true;
  33050. return _this;
  33051. }
  33052. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  33053. /**
  33054. * Gets the current transparency mode.
  33055. */
  33056. get: function () {
  33057. return this._transparencyMode;
  33058. },
  33059. /**
  33060. * Sets the transparency mode of the material.
  33061. */
  33062. set: function (value) {
  33063. if (this._transparencyMode === value) {
  33064. return;
  33065. }
  33066. this._transparencyMode = value;
  33067. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  33068. this._forceAlphaTest = true;
  33069. }
  33070. else {
  33071. this._forceAlphaTest = false;
  33072. }
  33073. this._markAllSubMeshesAsTexturesDirty();
  33074. },
  33075. enumerable: true,
  33076. configurable: true
  33077. });
  33078. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  33079. /**
  33080. * Gets the current double sided mode.
  33081. */
  33082. get: function () {
  33083. return this._twoSidedLighting;
  33084. },
  33085. /**
  33086. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33087. */
  33088. set: function (value) {
  33089. if (this._twoSidedLighting === value) {
  33090. return;
  33091. }
  33092. this._twoSidedLighting = value;
  33093. this.backFaceCulling = !value;
  33094. this._markAllSubMeshesAsTexturesDirty();
  33095. },
  33096. enumerable: true,
  33097. configurable: true
  33098. });
  33099. /**
  33100. * Specifies wether or not the alpha value of the albedo texture should be used.
  33101. */
  33102. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  33103. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  33104. };
  33105. /**
  33106. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  33107. */
  33108. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  33109. if (this._linkRefractionWithTransparency) {
  33110. return false;
  33111. }
  33112. return (this.alpha < 1.0) ||
  33113. (this._shouldUseAlphaFromAlbedoTexture() &&
  33114. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  33115. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  33116. };
  33117. /**
  33118. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  33119. */
  33120. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  33121. if (this._linkRefractionWithTransparency) {
  33122. return false;
  33123. }
  33124. return this._shouldUseAlphaFromAlbedoTexture() &&
  33125. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  33126. };
  33127. /**
  33128. * Return the active textures of the material.
  33129. */
  33130. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  33131. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33132. if (this.environmentTexture) {
  33133. activeTextures.push(this.environmentTexture);
  33134. }
  33135. if (this.normalTexture) {
  33136. activeTextures.push(this.normalTexture);
  33137. }
  33138. if (this.emissiveTexture) {
  33139. activeTextures.push(this.emissiveTexture);
  33140. }
  33141. if (this.occlusionTexture) {
  33142. activeTextures.push(this.occlusionTexture);
  33143. }
  33144. return activeTextures;
  33145. };
  33146. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  33147. return "PBRBaseSimpleMaterial";
  33148. };
  33149. __decorate([
  33150. BABYLON.serialize(),
  33151. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33152. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  33153. __decorate([
  33154. BABYLON.serialize(),
  33155. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33156. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  33157. __decorate([
  33158. BABYLON.serializeAsTexture(),
  33159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  33160. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  33161. __decorate([
  33162. BABYLON.serialize(),
  33163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33164. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  33165. __decorate([
  33166. BABYLON.serialize(),
  33167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33168. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  33169. __decorate([
  33170. BABYLON.serializeAsTexture(),
  33171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  33172. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  33173. __decorate([
  33174. BABYLON.serializeAsColor3("emissive"),
  33175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33176. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  33177. __decorate([
  33178. BABYLON.serializeAsTexture(),
  33179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33180. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  33181. __decorate([
  33182. BABYLON.serialize(),
  33183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  33184. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  33185. __decorate([
  33186. BABYLON.serializeAsTexture(),
  33187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  33188. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  33189. __decorate([
  33190. BABYLON.serialize(),
  33191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  33192. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  33193. __decorate([
  33194. BABYLON.serialize()
  33195. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  33196. __decorate([
  33197. BABYLON.serialize()
  33198. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  33199. return PBRBaseSimpleMaterial;
  33200. }(BABYLON.PBRBaseMaterial));
  33201. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  33202. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33203. })(BABYLON || (BABYLON = {}));
  33204. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  33205. var BABYLON;
  33206. (function (BABYLON) {
  33207. /**
  33208. * The Physically based material of BJS.
  33209. *
  33210. * This offers the main features of a standard PBR material.
  33211. * For more information, please refer to the documentation :
  33212. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  33213. */
  33214. var PBRMaterial = (function (_super) {
  33215. __extends(PBRMaterial, _super);
  33216. /**
  33217. * Instantiates a new PBRMaterial instance.
  33218. *
  33219. * @param name The material name
  33220. * @param scene The scene the material will be use in.
  33221. */
  33222. function PBRMaterial(name, scene) {
  33223. var _this = _super.call(this, name, scene) || this;
  33224. /**
  33225. * Intensity of the direct lights e.g. the four lights available in your scene.
  33226. * This impacts both the direct diffuse and specular highlights.
  33227. */
  33228. _this.directIntensity = 1.0;
  33229. /**
  33230. * Intensity of the emissive part of the material.
  33231. * This helps controlling the emissive effect without modifying the emissive color.
  33232. */
  33233. _this.emissiveIntensity = 1.0;
  33234. /**
  33235. * Intensity of the environment e.g. how much the environment will light the object
  33236. * either through harmonics for rough material or through the refelction for shiny ones.
  33237. */
  33238. _this.environmentIntensity = 1.0;
  33239. /**
  33240. * This is a special control allowing the reduction of the specular highlights coming from the
  33241. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  33242. */
  33243. _this.specularIntensity = 1.0;
  33244. /**
  33245. * Debug Control allowing disabling the bump map on this material.
  33246. */
  33247. _this.disableBumpMap = false;
  33248. /**
  33249. * AKA Occlusion Texture Intensity in other nomenclature.
  33250. */
  33251. _this.ambientTextureStrength = 1.0;
  33252. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33253. /**
  33254. * AKA Diffuse Color in other nomenclature.
  33255. */
  33256. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  33257. /**
  33258. * AKA Specular Color in other nomenclature.
  33259. */
  33260. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  33261. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  33262. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33263. /**
  33264. * AKA Glossiness in other nomenclature.
  33265. */
  33266. _this.microSurface = 1.0;
  33267. /**
  33268. * source material index of refraction (IOR)' / 'destination material IOR.
  33269. */
  33270. _this.indexOfRefraction = 0.66;
  33271. /**
  33272. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  33273. */
  33274. _this.invertRefractionY = false;
  33275. /**
  33276. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  33277. * Materials half opaque for instance using refraction could benefit from this control.
  33278. */
  33279. _this.linkRefractionWithTransparency = false;
  33280. _this.useLightmapAsShadowmap = false;
  33281. /**
  33282. * Specifies that the alpha is coming form the albedo channel alpha channel.
  33283. */
  33284. _this.useAlphaFromAlbedoTexture = false;
  33285. /**
  33286. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  33287. */
  33288. _this.forceAlphaTest = false;
  33289. /**
  33290. * Defines the alpha limits in alpha test mode.
  33291. */
  33292. _this.alphaCutOff = 0.4;
  33293. /**
  33294. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  33295. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  33296. */
  33297. _this.useSpecularOverAlpha = true;
  33298. /**
  33299. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  33300. */
  33301. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  33302. /**
  33303. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  33304. */
  33305. _this.useRoughnessFromMetallicTextureAlpha = true;
  33306. /**
  33307. * Specifies if the metallic texture contains the roughness information in its green channel.
  33308. */
  33309. _this.useRoughnessFromMetallicTextureGreen = false;
  33310. /**
  33311. * Specifies if the metallic texture contains the metallness information in its blue channel.
  33312. */
  33313. _this.useMetallnessFromMetallicTextureBlue = false;
  33314. /**
  33315. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  33316. */
  33317. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  33318. /**
  33319. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  33320. */
  33321. _this.useAmbientInGrayScale = false;
  33322. /**
  33323. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  33324. * The material will try to infer what glossiness each pixel should be.
  33325. */
  33326. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  33327. /**
  33328. * BJS is using an harcoded light falloff based on a manually sets up range.
  33329. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  33330. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  33331. */
  33332. _this.usePhysicalLightFalloff = true;
  33333. /**
  33334. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  33335. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  33336. */
  33337. _this.useRadianceOverAlpha = true;
  33338. /**
  33339. * Allows using the bump map in parallax mode.
  33340. */
  33341. _this.useParallax = false;
  33342. /**
  33343. * Allows using the bump map in parallax occlusion mode.
  33344. */
  33345. _this.useParallaxOcclusion = false;
  33346. /**
  33347. * Controls the scale bias of the parallax mode.
  33348. */
  33349. _this.parallaxScaleBias = 0.05;
  33350. /**
  33351. * If sets to true, disables all the lights affecting the material.
  33352. */
  33353. _this.disableLighting = false;
  33354. /**
  33355. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  33356. */
  33357. _this.forceIrradianceInFragment = false;
  33358. /**
  33359. * Number of Simultaneous lights allowed on the material.
  33360. */
  33361. _this.maxSimultaneousLights = 4;
  33362. /**
  33363. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33364. */
  33365. _this.invertNormalMapX = false;
  33366. /**
  33367. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33368. */
  33369. _this.invertNormalMapY = false;
  33370. /**
  33371. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33372. */
  33373. _this.twoSidedLighting = false;
  33374. /**
  33375. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  33376. * in your scene composition.
  33377. */
  33378. _this.preMultiplyAlpha = false;
  33379. /**
  33380. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33381. * And/Or occlude the blended part.
  33382. */
  33383. _this.useAlphaFresnel = false;
  33384. /**
  33385. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33386. * And/Or occlude the blended part.
  33387. */
  33388. _this.environmentBRDFTexture = null;
  33389. /**
  33390. * Force normal to face away from face.
  33391. * (Temporary internal fix to remove before 3.1)
  33392. */
  33393. _this.forceNormalForward = false;
  33394. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  33395. return _this;
  33396. }
  33397. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  33398. /**
  33399. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  33400. */
  33401. get: function () {
  33402. return this._PBRMATERIAL_OPAQUE;
  33403. },
  33404. enumerable: true,
  33405. configurable: true
  33406. });
  33407. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  33408. /**
  33409. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  33410. */
  33411. get: function () {
  33412. return this._PBRMATERIAL_ALPHATEST;
  33413. },
  33414. enumerable: true,
  33415. configurable: true
  33416. });
  33417. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  33418. /**
  33419. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33420. */
  33421. get: function () {
  33422. return this._PBRMATERIAL_ALPHABLEND;
  33423. },
  33424. enumerable: true,
  33425. configurable: true
  33426. });
  33427. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  33428. /**
  33429. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33430. * They are also discarded below the alpha cutoff threshold to improve performances.
  33431. */
  33432. get: function () {
  33433. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  33434. },
  33435. enumerable: true,
  33436. configurable: true
  33437. });
  33438. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  33439. /**
  33440. * Gets the image processing configuration used either in this material.
  33441. */
  33442. get: function () {
  33443. return this._imageProcessingConfiguration;
  33444. },
  33445. /**
  33446. * Sets the Default image processing configuration used either in the this material.
  33447. *
  33448. * If sets to null, the scene one is in use.
  33449. */
  33450. set: function (value) {
  33451. this._attachImageProcessingConfiguration(value);
  33452. // Ensure the effect will be rebuilt.
  33453. this._markAllSubMeshesAsTexturesDirty();
  33454. },
  33455. enumerable: true,
  33456. configurable: true
  33457. });
  33458. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  33459. /**
  33460. * Gets wether the color curves effect is enabled.
  33461. */
  33462. get: function () {
  33463. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33464. },
  33465. /**
  33466. * Sets wether the color curves effect is enabled.
  33467. */
  33468. set: function (value) {
  33469. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33470. },
  33471. enumerable: true,
  33472. configurable: true
  33473. });
  33474. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  33475. /**
  33476. * Gets wether the color grading effect is enabled.
  33477. */
  33478. get: function () {
  33479. return this.imageProcessingConfiguration.colorGradingEnabled;
  33480. },
  33481. /**
  33482. * Gets wether the color grading effect is enabled.
  33483. */
  33484. set: function (value) {
  33485. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33486. },
  33487. enumerable: true,
  33488. configurable: true
  33489. });
  33490. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  33491. /**
  33492. * Gets wether tonemapping is enabled or not.
  33493. */
  33494. get: function () {
  33495. return this._imageProcessingConfiguration.toneMappingEnabled;
  33496. },
  33497. /**
  33498. * Sets wether tonemapping is enabled or not
  33499. */
  33500. set: function (value) {
  33501. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33502. },
  33503. enumerable: true,
  33504. configurable: true
  33505. });
  33506. ;
  33507. ;
  33508. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  33509. /**
  33510. * The camera exposure used on this material.
  33511. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33512. * This corresponds to a photographic exposure.
  33513. */
  33514. get: function () {
  33515. return this._imageProcessingConfiguration.exposure;
  33516. },
  33517. /**
  33518. * The camera exposure used on this material.
  33519. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33520. * This corresponds to a photographic exposure.
  33521. */
  33522. set: function (value) {
  33523. this._imageProcessingConfiguration.exposure = value;
  33524. },
  33525. enumerable: true,
  33526. configurable: true
  33527. });
  33528. ;
  33529. ;
  33530. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  33531. /**
  33532. * Gets The camera contrast used on this material.
  33533. */
  33534. get: function () {
  33535. return this._imageProcessingConfiguration.contrast;
  33536. },
  33537. /**
  33538. * Sets The camera contrast used on this material.
  33539. */
  33540. set: function (value) {
  33541. this._imageProcessingConfiguration.contrast = value;
  33542. },
  33543. enumerable: true,
  33544. configurable: true
  33545. });
  33546. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  33547. /**
  33548. * Gets the Color Grading 2D Lookup Texture.
  33549. */
  33550. get: function () {
  33551. return this._imageProcessingConfiguration.colorGradingTexture;
  33552. },
  33553. /**
  33554. * Sets the Color Grading 2D Lookup Texture.
  33555. */
  33556. set: function (value) {
  33557. this._imageProcessingConfiguration.colorGradingTexture = value;
  33558. },
  33559. enumerable: true,
  33560. configurable: true
  33561. });
  33562. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  33563. /**
  33564. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33565. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33566. * 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;
  33567. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33568. */
  33569. get: function () {
  33570. return this._imageProcessingConfiguration.colorCurves;
  33571. },
  33572. /**
  33573. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33574. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33575. * 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;
  33576. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33577. */
  33578. set: function (value) {
  33579. this._imageProcessingConfiguration.colorCurves = value;
  33580. },
  33581. enumerable: true,
  33582. configurable: true
  33583. });
  33584. PBRMaterial.prototype.getClassName = function () {
  33585. return "PBRMaterial";
  33586. };
  33587. PBRMaterial.prototype.getActiveTextures = function () {
  33588. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33589. if (this._albedoTexture) {
  33590. activeTextures.push(this._albedoTexture);
  33591. }
  33592. if (this._ambientTexture) {
  33593. activeTextures.push(this._ambientTexture);
  33594. }
  33595. if (this._opacityTexture) {
  33596. activeTextures.push(this._opacityTexture);
  33597. }
  33598. if (this._reflectionTexture) {
  33599. activeTextures.push(this._reflectionTexture);
  33600. }
  33601. if (this._emissiveTexture) {
  33602. activeTextures.push(this._emissiveTexture);
  33603. }
  33604. if (this._reflectivityTexture) {
  33605. activeTextures.push(this._reflectivityTexture);
  33606. }
  33607. if (this._metallicTexture) {
  33608. activeTextures.push(this._metallicTexture);
  33609. }
  33610. if (this._microSurfaceTexture) {
  33611. activeTextures.push(this._microSurfaceTexture);
  33612. }
  33613. if (this._bumpTexture) {
  33614. activeTextures.push(this._bumpTexture);
  33615. }
  33616. if (this._lightmapTexture) {
  33617. activeTextures.push(this._lightmapTexture);
  33618. }
  33619. if (this._refractionTexture) {
  33620. activeTextures.push(this._refractionTexture);
  33621. }
  33622. return activeTextures;
  33623. };
  33624. PBRMaterial.prototype.hasTexture = function (texture) {
  33625. if (_super.prototype.hasTexture.call(this, texture)) {
  33626. return true;
  33627. }
  33628. if (this._albedoTexture === texture) {
  33629. return true;
  33630. }
  33631. if (this._ambientTexture === texture) {
  33632. return true;
  33633. }
  33634. if (this._opacityTexture === texture) {
  33635. return true;
  33636. }
  33637. if (this._reflectionTexture === texture) {
  33638. return true;
  33639. }
  33640. if (this._reflectivityTexture === texture) {
  33641. return true;
  33642. }
  33643. if (this._metallicTexture === texture) {
  33644. return true;
  33645. }
  33646. if (this._microSurfaceTexture === texture) {
  33647. return true;
  33648. }
  33649. if (this._bumpTexture === texture) {
  33650. return true;
  33651. }
  33652. if (this._lightmapTexture === texture) {
  33653. return true;
  33654. }
  33655. if (this._refractionTexture === texture) {
  33656. return true;
  33657. }
  33658. return false;
  33659. };
  33660. PBRMaterial.prototype.clone = function (name) {
  33661. var _this = this;
  33662. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  33663. };
  33664. PBRMaterial.prototype.serialize = function () {
  33665. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33666. serializationObject.customType = "BABYLON.PBRMaterial";
  33667. return serializationObject;
  33668. };
  33669. // Statics
  33670. PBRMaterial.Parse = function (source, scene, rootUrl) {
  33671. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  33672. };
  33673. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  33674. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  33675. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  33676. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  33677. __decorate([
  33678. BABYLON.serialize(),
  33679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33680. ], PBRMaterial.prototype, "directIntensity", void 0);
  33681. __decorate([
  33682. BABYLON.serialize(),
  33683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33684. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  33685. __decorate([
  33686. BABYLON.serialize(),
  33687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33688. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  33689. __decorate([
  33690. BABYLON.serialize(),
  33691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33692. ], PBRMaterial.prototype, "specularIntensity", void 0);
  33693. __decorate([
  33694. BABYLON.serialize(),
  33695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33696. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  33697. __decorate([
  33698. BABYLON.serializeAsTexture(),
  33699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33700. ], PBRMaterial.prototype, "albedoTexture", void 0);
  33701. __decorate([
  33702. BABYLON.serializeAsTexture(),
  33703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33704. ], PBRMaterial.prototype, "ambientTexture", void 0);
  33705. __decorate([
  33706. BABYLON.serialize(),
  33707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33708. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  33709. __decorate([
  33710. BABYLON.serializeAsTexture(),
  33711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33712. ], PBRMaterial.prototype, "opacityTexture", void 0);
  33713. __decorate([
  33714. BABYLON.serializeAsTexture(),
  33715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33716. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  33717. __decorate([
  33718. BABYLON.serializeAsTexture(),
  33719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33720. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  33721. __decorate([
  33722. BABYLON.serializeAsTexture(),
  33723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33724. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  33725. __decorate([
  33726. BABYLON.serializeAsTexture(),
  33727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33728. ], PBRMaterial.prototype, "metallicTexture", void 0);
  33729. __decorate([
  33730. BABYLON.serialize(),
  33731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33732. ], PBRMaterial.prototype, "metallic", void 0);
  33733. __decorate([
  33734. BABYLON.serialize(),
  33735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33736. ], PBRMaterial.prototype, "roughness", void 0);
  33737. __decorate([
  33738. BABYLON.serializeAsTexture(),
  33739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33740. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  33741. __decorate([
  33742. BABYLON.serializeAsTexture(),
  33743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33744. ], PBRMaterial.prototype, "bumpTexture", void 0);
  33745. __decorate([
  33746. BABYLON.serializeAsTexture(),
  33747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  33748. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  33749. __decorate([
  33750. BABYLON.serializeAsTexture(),
  33751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33752. ], PBRMaterial.prototype, "refractionTexture", void 0);
  33753. __decorate([
  33754. BABYLON.serializeAsColor3("ambient"),
  33755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33756. ], PBRMaterial.prototype, "ambientColor", void 0);
  33757. __decorate([
  33758. BABYLON.serializeAsColor3("albedo"),
  33759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33760. ], PBRMaterial.prototype, "albedoColor", void 0);
  33761. __decorate([
  33762. BABYLON.serializeAsColor3("reflectivity"),
  33763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33764. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  33765. __decorate([
  33766. BABYLON.serializeAsColor3("reflection"),
  33767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33768. ], PBRMaterial.prototype, "reflectionColor", void 0);
  33769. __decorate([
  33770. BABYLON.serializeAsColor3("emissive"),
  33771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33772. ], PBRMaterial.prototype, "emissiveColor", void 0);
  33773. __decorate([
  33774. BABYLON.serialize(),
  33775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33776. ], PBRMaterial.prototype, "microSurface", void 0);
  33777. __decorate([
  33778. BABYLON.serialize(),
  33779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33780. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  33781. __decorate([
  33782. BABYLON.serialize(),
  33783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33784. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  33785. __decorate([
  33786. BABYLON.serialize(),
  33787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33788. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  33789. __decorate([
  33790. BABYLON.serialize(),
  33791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33792. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33793. __decorate([
  33794. BABYLON.serialize(),
  33795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33796. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  33797. __decorate([
  33798. BABYLON.serialize(),
  33799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33800. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  33801. __decorate([
  33802. BABYLON.serialize(),
  33803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33804. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  33805. __decorate([
  33806. BABYLON.serialize(),
  33807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33808. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  33809. __decorate([
  33810. BABYLON.serialize(),
  33811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33812. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  33813. __decorate([
  33814. BABYLON.serialize(),
  33815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33816. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  33817. __decorate([
  33818. BABYLON.serialize(),
  33819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33820. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  33821. __decorate([
  33822. BABYLON.serialize(),
  33823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33824. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  33825. __decorate([
  33826. BABYLON.serialize(),
  33827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33828. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  33829. __decorate([
  33830. BABYLON.serialize(),
  33831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33832. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  33833. __decorate([
  33834. BABYLON.serialize(),
  33835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33836. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  33837. __decorate([
  33838. BABYLON.serialize(),
  33839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33840. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  33841. __decorate([
  33842. BABYLON.serialize(),
  33843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33844. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  33845. __decorate([
  33846. BABYLON.serialize(),
  33847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33848. ], PBRMaterial.prototype, "useParallax", void 0);
  33849. __decorate([
  33850. BABYLON.serialize(),
  33851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33852. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  33853. __decorate([
  33854. BABYLON.serialize(),
  33855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33856. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  33857. __decorate([
  33858. BABYLON.serialize(),
  33859. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33860. ], PBRMaterial.prototype, "disableLighting", void 0);
  33861. __decorate([
  33862. BABYLON.serialize(),
  33863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33864. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  33865. __decorate([
  33866. BABYLON.serialize(),
  33867. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33868. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  33869. __decorate([
  33870. BABYLON.serialize(),
  33871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33872. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  33873. __decorate([
  33874. BABYLON.serialize(),
  33875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33876. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  33877. __decorate([
  33878. BABYLON.serialize(),
  33879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33880. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  33881. __decorate([
  33882. BABYLON.serialize(),
  33883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33884. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  33885. __decorate([
  33886. BABYLON.serialize(),
  33887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33888. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  33889. __decorate([
  33890. BABYLON.serializeAsTexture(),
  33891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33892. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  33893. __decorate([
  33894. BABYLON.serialize(),
  33895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33896. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  33897. return PBRMaterial;
  33898. }(BABYLON.PBRBaseMaterial));
  33899. BABYLON.PBRMaterial = PBRMaterial;
  33900. })(BABYLON || (BABYLON = {}));
  33901. //# sourceMappingURL=babylon.pbrMaterial.js.map
  33902. var BABYLON;
  33903. (function (BABYLON) {
  33904. /**
  33905. * The PBR material of BJS following the metal roughness convention.
  33906. *
  33907. * This fits to the PBR convention in the GLTF definition:
  33908. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  33909. */
  33910. var PBRMetallicRoughnessMaterial = (function (_super) {
  33911. __extends(PBRMetallicRoughnessMaterial, _super);
  33912. /**
  33913. * Instantiates a new PBRMetalRoughnessMaterial instance.
  33914. *
  33915. * @param name The material name
  33916. * @param scene The scene the material will be use in.
  33917. */
  33918. function PBRMetallicRoughnessMaterial(name, scene) {
  33919. var _this = _super.call(this, name, scene) || this;
  33920. _this._useRoughnessFromMetallicTextureAlpha = false;
  33921. _this._useRoughnessFromMetallicTextureGreen = true;
  33922. _this._useMetallnessFromMetallicTextureBlue = true;
  33923. return _this;
  33924. }
  33925. /**
  33926. * Return the currrent class name of the material.
  33927. */
  33928. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  33929. return "PBRMetallicRoughnessMaterial";
  33930. };
  33931. /**
  33932. * Return the active textures of the material.
  33933. */
  33934. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  33935. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33936. if (this.baseTexture) {
  33937. activeTextures.push(this.baseTexture);
  33938. }
  33939. if (this.metallicRoughnessTexture) {
  33940. activeTextures.push(this.metallicRoughnessTexture);
  33941. }
  33942. return activeTextures;
  33943. };
  33944. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  33945. if (_super.prototype.hasTexture.call(this, texture)) {
  33946. return true;
  33947. }
  33948. if (this.baseTexture === texture) {
  33949. return true;
  33950. }
  33951. if (this.metallicRoughnessTexture === texture) {
  33952. return true;
  33953. }
  33954. return false;
  33955. };
  33956. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  33957. var _this = this;
  33958. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  33959. };
  33960. /**
  33961. * Serialize the material to a parsable JSON object.
  33962. */
  33963. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  33964. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33965. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  33966. return serializationObject;
  33967. };
  33968. /**
  33969. * Parses a JSON object correponding to the serialize function.
  33970. */
  33971. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  33972. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  33973. };
  33974. __decorate([
  33975. BABYLON.serializeAsColor3(),
  33976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33977. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  33978. __decorate([
  33979. BABYLON.serializeAsTexture(),
  33980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33981. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  33982. __decorate([
  33983. BABYLON.serialize(),
  33984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33985. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  33986. __decorate([
  33987. BABYLON.serialize(),
  33988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33989. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  33990. __decorate([
  33991. BABYLON.serializeAsTexture(),
  33992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  33993. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  33994. return PBRMetallicRoughnessMaterial;
  33995. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33996. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  33997. })(BABYLON || (BABYLON = {}));
  33998. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  33999. var BABYLON;
  34000. (function (BABYLON) {
  34001. /**
  34002. * The PBR material of BJS following the specular glossiness convention.
  34003. *
  34004. * This fits to the PBR convention in the GLTF definition:
  34005. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  34006. */
  34007. var PBRSpecularGlossinessMaterial = (function (_super) {
  34008. __extends(PBRSpecularGlossinessMaterial, _super);
  34009. /**
  34010. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  34011. *
  34012. * @param name The material name
  34013. * @param scene The scene the material will be use in.
  34014. */
  34015. function PBRSpecularGlossinessMaterial(name, scene) {
  34016. var _this = _super.call(this, name, scene) || this;
  34017. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  34018. return _this;
  34019. }
  34020. /**
  34021. * Return the currrent class name of the material.
  34022. */
  34023. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  34024. return "PBRSpecularGlossinessMaterial";
  34025. };
  34026. /**
  34027. * Return the active textures of the material.
  34028. */
  34029. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  34030. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34031. if (this.diffuseTexture) {
  34032. activeTextures.push(this.diffuseTexture);
  34033. }
  34034. if (this.specularGlossinessTexture) {
  34035. activeTextures.push(this.specularGlossinessTexture);
  34036. }
  34037. return activeTextures;
  34038. };
  34039. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  34040. if (_super.prototype.hasTexture.call(this, texture)) {
  34041. return true;
  34042. }
  34043. if (this.diffuseTexture === texture) {
  34044. return true;
  34045. }
  34046. if (this.specularGlossinessTexture === texture) {
  34047. return true;
  34048. }
  34049. return false;
  34050. };
  34051. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  34052. var _this = this;
  34053. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  34054. };
  34055. /**
  34056. * Serialize the material to a parsable JSON object.
  34057. */
  34058. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  34059. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34060. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  34061. return serializationObject;
  34062. };
  34063. /**
  34064. * Parses a JSON object correponding to the serialize function.
  34065. */
  34066. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  34067. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  34068. };
  34069. __decorate([
  34070. BABYLON.serializeAsColor3("diffuse"),
  34071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  34072. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  34073. __decorate([
  34074. BABYLON.serializeAsTexture(),
  34075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  34076. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  34077. __decorate([
  34078. BABYLON.serializeAsColor3("specular"),
  34079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  34080. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  34081. __decorate([
  34082. BABYLON.serialize(),
  34083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  34084. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  34085. __decorate([
  34086. BABYLON.serializeAsTexture(),
  34087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  34088. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  34089. return PBRSpecularGlossinessMaterial;
  34090. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  34091. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  34092. })(BABYLON || (BABYLON = {}));
  34093. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  34094. var BABYLON;
  34095. (function (BABYLON) {
  34096. BABYLON.CameraInputTypes = {};
  34097. var CameraInputsManager = (function () {
  34098. function CameraInputsManager(camera) {
  34099. this.attached = {};
  34100. this.camera = camera;
  34101. this.checkInputs = function () { };
  34102. }
  34103. CameraInputsManager.prototype.add = function (input) {
  34104. var type = input.getSimpleName();
  34105. if (this.attached[type]) {
  34106. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  34107. return;
  34108. }
  34109. this.attached[type] = input;
  34110. input.camera = this.camera;
  34111. //for checkInputs, we are dynamically creating a function
  34112. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  34113. if (input.checkInputs) {
  34114. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34115. }
  34116. if (this.attachedElement) {
  34117. input.attachControl(this.attachedElement);
  34118. }
  34119. };
  34120. CameraInputsManager.prototype.remove = function (inputToRemove) {
  34121. for (var cam in this.attached) {
  34122. var input = this.attached[cam];
  34123. if (input === inputToRemove) {
  34124. input.detachControl(this.attachedElement);
  34125. input.camera = null;
  34126. delete this.attached[cam];
  34127. this.rebuildInputCheck();
  34128. }
  34129. }
  34130. };
  34131. CameraInputsManager.prototype.removeByType = function (inputType) {
  34132. for (var cam in this.attached) {
  34133. var input = this.attached[cam];
  34134. if (input.getClassName() === inputType) {
  34135. input.detachControl(this.attachedElement);
  34136. input.camera = null;
  34137. delete this.attached[cam];
  34138. this.rebuildInputCheck();
  34139. }
  34140. }
  34141. };
  34142. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  34143. var current = this.checkInputs;
  34144. return function () {
  34145. current();
  34146. fn();
  34147. };
  34148. };
  34149. CameraInputsManager.prototype.attachInput = function (input) {
  34150. input.attachControl(this.attachedElement, this.noPreventDefault);
  34151. };
  34152. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  34153. if (this.attachedElement) {
  34154. return;
  34155. }
  34156. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  34157. this.attachedElement = element;
  34158. this.noPreventDefault = noPreventDefault;
  34159. for (var cam in this.attached) {
  34160. var input = this.attached[cam];
  34161. this.attached[cam].attachControl(element, noPreventDefault);
  34162. }
  34163. };
  34164. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  34165. if (disconnect === void 0) { disconnect = false; }
  34166. if (this.attachedElement !== element) {
  34167. return;
  34168. }
  34169. for (var cam in this.attached) {
  34170. var input = this.attached[cam];
  34171. this.attached[cam].detachControl(element);
  34172. if (disconnect) {
  34173. this.attached[cam].camera = null;
  34174. }
  34175. }
  34176. this.attachedElement = null;
  34177. };
  34178. CameraInputsManager.prototype.rebuildInputCheck = function () {
  34179. this.checkInputs = function () { };
  34180. for (var cam in this.attached) {
  34181. var input = this.attached[cam];
  34182. if (input.checkInputs) {
  34183. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34184. }
  34185. }
  34186. };
  34187. CameraInputsManager.prototype.clear = function () {
  34188. if (this.attachedElement) {
  34189. this.detachElement(this.attachedElement, true);
  34190. }
  34191. this.attached = {};
  34192. this.attachedElement = null;
  34193. this.checkInputs = function () { };
  34194. };
  34195. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  34196. var inputs = {};
  34197. for (var cam in this.attached) {
  34198. var input = this.attached[cam];
  34199. var res = BABYLON.SerializationHelper.Serialize(input);
  34200. inputs[input.getClassName()] = res;
  34201. }
  34202. serializedCamera.inputsmgr = inputs;
  34203. };
  34204. CameraInputsManager.prototype.parse = function (parsedCamera) {
  34205. var parsedInputs = parsedCamera.inputsmgr;
  34206. if (parsedInputs) {
  34207. this.clear();
  34208. for (var n in parsedInputs) {
  34209. var construct = BABYLON.CameraInputTypes[n];
  34210. if (construct) {
  34211. var parsedinput = parsedInputs[n];
  34212. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  34213. this.add(input);
  34214. }
  34215. }
  34216. }
  34217. else {
  34218. //2016-03-08 this part is for managing backward compatibility
  34219. for (var n in this.attached) {
  34220. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  34221. if (construct) {
  34222. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  34223. this.remove(this.attached[n]);
  34224. this.add(input);
  34225. }
  34226. }
  34227. }
  34228. };
  34229. return CameraInputsManager;
  34230. }());
  34231. BABYLON.CameraInputsManager = CameraInputsManager;
  34232. })(BABYLON || (BABYLON = {}));
  34233. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  34234. var BABYLON;
  34235. (function (BABYLON) {
  34236. var FreeCameraMouseInput = (function () {
  34237. function FreeCameraMouseInput(touchEnabled) {
  34238. if (touchEnabled === void 0) { touchEnabled = true; }
  34239. this.touchEnabled = touchEnabled;
  34240. this.buttons = [0, 1, 2];
  34241. this.angularSensibility = 2000.0;
  34242. }
  34243. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  34244. var _this = this;
  34245. var engine = this.camera.getEngine();
  34246. if (!this._pointerInput) {
  34247. this._pointerInput = function (p, s) {
  34248. var evt = p.event;
  34249. if (engine.isInVRExclusivePointerMode) {
  34250. return;
  34251. }
  34252. if (!_this.touchEnabled && evt.pointerType === "touch") {
  34253. return;
  34254. }
  34255. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34256. return;
  34257. }
  34258. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34259. try {
  34260. evt.srcElement.setPointerCapture(evt.pointerId);
  34261. }
  34262. catch (e) {
  34263. //Nothing to do with the error. Execution will continue.
  34264. }
  34265. _this.previousPosition = {
  34266. x: evt.clientX,
  34267. y: evt.clientY
  34268. };
  34269. if (!noPreventDefault) {
  34270. evt.preventDefault();
  34271. element.focus();
  34272. }
  34273. }
  34274. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34275. try {
  34276. evt.srcElement.releasePointerCapture(evt.pointerId);
  34277. }
  34278. catch (e) {
  34279. //Nothing to do with the error.
  34280. }
  34281. _this.previousPosition = null;
  34282. if (!noPreventDefault) {
  34283. evt.preventDefault();
  34284. }
  34285. }
  34286. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34287. if (!_this.previousPosition || engine.isPointerLock) {
  34288. return;
  34289. }
  34290. var offsetX = evt.clientX - _this.previousPosition.x;
  34291. var offsetY = evt.clientY - _this.previousPosition.y;
  34292. if (_this.camera.getScene().useRightHandedSystem) {
  34293. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34294. }
  34295. else {
  34296. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34297. }
  34298. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34299. _this.previousPosition = {
  34300. x: evt.clientX,
  34301. y: evt.clientY
  34302. };
  34303. if (!noPreventDefault) {
  34304. evt.preventDefault();
  34305. }
  34306. }
  34307. };
  34308. }
  34309. this._onMouseMove = function (evt) {
  34310. if (!engine.isPointerLock) {
  34311. return;
  34312. }
  34313. if (engine.isInVRExclusivePointerMode) {
  34314. return;
  34315. }
  34316. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34317. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34318. if (_this.camera.getScene().useRightHandedSystem) {
  34319. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34320. }
  34321. else {
  34322. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34323. }
  34324. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34325. _this.previousPosition = null;
  34326. if (!noPreventDefault) {
  34327. evt.preventDefault();
  34328. }
  34329. };
  34330. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34331. element.addEventListener("mousemove", this._onMouseMove, false);
  34332. };
  34333. FreeCameraMouseInput.prototype.detachControl = function (element) {
  34334. if (this._observer && element) {
  34335. this.camera.getScene().onPointerObservable.remove(this._observer);
  34336. element.removeEventListener("mousemove", this._onMouseMove);
  34337. this._observer = null;
  34338. this._onMouseMove = null;
  34339. this.previousPosition = null;
  34340. }
  34341. };
  34342. FreeCameraMouseInput.prototype.getClassName = function () {
  34343. return "FreeCameraMouseInput";
  34344. };
  34345. FreeCameraMouseInput.prototype.getSimpleName = function () {
  34346. return "mouse";
  34347. };
  34348. __decorate([
  34349. BABYLON.serialize()
  34350. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  34351. __decorate([
  34352. BABYLON.serialize()
  34353. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  34354. return FreeCameraMouseInput;
  34355. }());
  34356. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  34357. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  34358. })(BABYLON || (BABYLON = {}));
  34359. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  34360. var BABYLON;
  34361. (function (BABYLON) {
  34362. var FreeCameraKeyboardMoveInput = (function () {
  34363. function FreeCameraKeyboardMoveInput() {
  34364. this._keys = [];
  34365. this.keysUp = [38];
  34366. this.keysDown = [40];
  34367. this.keysLeft = [37];
  34368. this.keysRight = [39];
  34369. }
  34370. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34371. var _this = this;
  34372. if (this._onCanvasBlurObserver) {
  34373. return;
  34374. }
  34375. this._scene = this.camera.getScene();
  34376. this._engine = this._scene.getEngine();
  34377. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  34378. _this._keys = [];
  34379. });
  34380. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  34381. var evt = info.event;
  34382. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  34383. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34384. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34385. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34386. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34387. var index = _this._keys.indexOf(evt.keyCode);
  34388. if (index === -1) {
  34389. _this._keys.push(evt.keyCode);
  34390. }
  34391. if (!noPreventDefault) {
  34392. evt.preventDefault();
  34393. }
  34394. }
  34395. }
  34396. else {
  34397. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34398. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34399. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34400. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34401. var index = _this._keys.indexOf(evt.keyCode);
  34402. if (index >= 0) {
  34403. _this._keys.splice(index, 1);
  34404. }
  34405. if (!noPreventDefault) {
  34406. evt.preventDefault();
  34407. }
  34408. }
  34409. }
  34410. });
  34411. };
  34412. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34413. if (this._scene) {
  34414. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  34415. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  34416. this._onKeyboardObserver = null;
  34417. this._onCanvasBlurObserver = null;
  34418. }
  34419. this._keys = [];
  34420. };
  34421. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34422. if (this._onKeyboardObserver) {
  34423. var camera = this.camera;
  34424. // Keyboard
  34425. for (var index = 0; index < this._keys.length; index++) {
  34426. var keyCode = this._keys[index];
  34427. var speed = camera._computeLocalCameraSpeed();
  34428. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34429. camera._localDirection.copyFromFloats(-speed, 0, 0);
  34430. }
  34431. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34432. camera._localDirection.copyFromFloats(0, 0, speed);
  34433. }
  34434. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34435. camera._localDirection.copyFromFloats(speed, 0, 0);
  34436. }
  34437. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34438. camera._localDirection.copyFromFloats(0, 0, -speed);
  34439. }
  34440. if (camera.getScene().useRightHandedSystem) {
  34441. camera._localDirection.z *= -1;
  34442. }
  34443. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  34444. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  34445. camera.cameraDirection.addInPlace(camera._transformedDirection);
  34446. }
  34447. }
  34448. };
  34449. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  34450. return "FreeCameraKeyboardMoveInput";
  34451. };
  34452. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  34453. this._keys = [];
  34454. };
  34455. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34456. return "keyboard";
  34457. };
  34458. __decorate([
  34459. BABYLON.serialize()
  34460. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34461. __decorate([
  34462. BABYLON.serialize()
  34463. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34464. __decorate([
  34465. BABYLON.serialize()
  34466. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34467. __decorate([
  34468. BABYLON.serialize()
  34469. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34470. return FreeCameraKeyboardMoveInput;
  34471. }());
  34472. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  34473. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  34474. })(BABYLON || (BABYLON = {}));
  34475. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  34476. var BABYLON;
  34477. (function (BABYLON) {
  34478. var FreeCameraInputsManager = (function (_super) {
  34479. __extends(FreeCameraInputsManager, _super);
  34480. function FreeCameraInputsManager(camera) {
  34481. return _super.call(this, camera) || this;
  34482. }
  34483. FreeCameraInputsManager.prototype.addKeyboard = function () {
  34484. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  34485. return this;
  34486. };
  34487. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  34488. if (touchEnabled === void 0) { touchEnabled = true; }
  34489. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  34490. return this;
  34491. };
  34492. FreeCameraInputsManager.prototype.addGamepad = function () {
  34493. this.add(new BABYLON.FreeCameraGamepadInput());
  34494. return this;
  34495. };
  34496. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  34497. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  34498. return this;
  34499. };
  34500. FreeCameraInputsManager.prototype.addTouch = function () {
  34501. this.add(new BABYLON.FreeCameraTouchInput());
  34502. return this;
  34503. };
  34504. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  34505. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  34506. return this;
  34507. };
  34508. return FreeCameraInputsManager;
  34509. }(BABYLON.CameraInputsManager));
  34510. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  34511. })(BABYLON || (BABYLON = {}));
  34512. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  34513. /// <reference path="babylon.camera.ts" />
  34514. var BABYLON;
  34515. (function (BABYLON) {
  34516. var TargetCamera = (function (_super) {
  34517. __extends(TargetCamera, _super);
  34518. function TargetCamera(name, position, scene) {
  34519. var _this = _super.call(this, name, position, scene) || this;
  34520. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34521. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  34522. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  34523. _this.speed = 2.0;
  34524. _this.noRotationConstraint = false;
  34525. _this.lockedTarget = null;
  34526. _this._currentTarget = BABYLON.Vector3.Zero();
  34527. _this._viewMatrix = BABYLON.Matrix.Zero();
  34528. _this._camMatrix = BABYLON.Matrix.Zero();
  34529. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  34530. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  34531. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  34532. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  34533. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  34534. _this._lookAtTemp = BABYLON.Matrix.Zero();
  34535. _this._tempMatrix = BABYLON.Matrix.Zero();
  34536. return _this;
  34537. }
  34538. TargetCamera.prototype.getFrontPosition = function (distance) {
  34539. var direction = this.getTarget().subtract(this.position);
  34540. direction.normalize();
  34541. direction.scaleInPlace(distance);
  34542. return this.globalPosition.add(direction);
  34543. };
  34544. TargetCamera.prototype._getLockedTargetPosition = function () {
  34545. if (!this.lockedTarget) {
  34546. return null;
  34547. }
  34548. if (this.lockedTarget.absolutePosition) {
  34549. this.lockedTarget.computeWorldMatrix();
  34550. }
  34551. return this.lockedTarget.absolutePosition || this.lockedTarget;
  34552. };
  34553. TargetCamera.prototype.storeState = function () {
  34554. this._storedPosition = this.position.clone();
  34555. this._storedRotation = this.rotation.clone();
  34556. if (this.rotationQuaternion) {
  34557. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  34558. }
  34559. return _super.prototype.storeState.call(this);
  34560. };
  34561. /**
  34562. * Restored camera state. You must call storeState() first
  34563. */
  34564. TargetCamera.prototype._restoreStateValues = function () {
  34565. if (!_super.prototype._restoreStateValues.call(this)) {
  34566. return false;
  34567. }
  34568. this.position = this._storedPosition.clone();
  34569. this.rotation = this._storedRotation.clone();
  34570. if (this.rotationQuaternion) {
  34571. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  34572. }
  34573. this.cameraDirection.copyFromFloats(0, 0, 0);
  34574. this.cameraRotation.copyFromFloats(0, 0);
  34575. return true;
  34576. };
  34577. // Cache
  34578. TargetCamera.prototype._initCache = function () {
  34579. _super.prototype._initCache.call(this);
  34580. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34581. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34582. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34583. };
  34584. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  34585. if (!ignoreParentClass) {
  34586. _super.prototype._updateCache.call(this);
  34587. }
  34588. var lockedTargetPosition = this._getLockedTargetPosition();
  34589. if (!lockedTargetPosition) {
  34590. this._cache.lockedTarget = null;
  34591. }
  34592. else {
  34593. if (!this._cache.lockedTarget) {
  34594. this._cache.lockedTarget = lockedTargetPosition.clone();
  34595. }
  34596. else {
  34597. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  34598. }
  34599. }
  34600. this._cache.rotation.copyFrom(this.rotation);
  34601. if (this.rotationQuaternion)
  34602. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34603. };
  34604. // Synchronized
  34605. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  34606. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  34607. return false;
  34608. }
  34609. var lockedTargetPosition = this._getLockedTargetPosition();
  34610. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  34611. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  34612. };
  34613. // Methods
  34614. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  34615. var engine = this.getEngine();
  34616. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  34617. };
  34618. // Target
  34619. TargetCamera.prototype.setTarget = function (target) {
  34620. this.upVector.normalize();
  34621. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  34622. this._camMatrix.invert();
  34623. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  34624. var vDir = target.subtract(this.position);
  34625. if (vDir.x >= 0.0) {
  34626. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  34627. }
  34628. else {
  34629. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  34630. }
  34631. this.rotation.z = 0;
  34632. if (isNaN(this.rotation.x)) {
  34633. this.rotation.x = 0;
  34634. }
  34635. if (isNaN(this.rotation.y)) {
  34636. this.rotation.y = 0;
  34637. }
  34638. if (isNaN(this.rotation.z)) {
  34639. this.rotation.z = 0;
  34640. }
  34641. if (this.rotationQuaternion) {
  34642. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34643. }
  34644. };
  34645. /**
  34646. * Return the current target position of the camera. This value is expressed in local space.
  34647. */
  34648. TargetCamera.prototype.getTarget = function () {
  34649. return this._currentTarget;
  34650. };
  34651. TargetCamera.prototype._decideIfNeedsToMove = function () {
  34652. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34653. };
  34654. TargetCamera.prototype._updatePosition = function () {
  34655. if (this.parent) {
  34656. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  34657. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  34658. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  34659. return;
  34660. }
  34661. this.position.addInPlace(this.cameraDirection);
  34662. };
  34663. TargetCamera.prototype._checkInputs = function () {
  34664. var needToMove = this._decideIfNeedsToMove();
  34665. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  34666. // Move
  34667. if (needToMove) {
  34668. this._updatePosition();
  34669. }
  34670. // Rotate
  34671. if (needToRotate) {
  34672. this.rotation.x += this.cameraRotation.x;
  34673. this.rotation.y += this.cameraRotation.y;
  34674. //rotate, if quaternion is set and rotation was used
  34675. if (this.rotationQuaternion) {
  34676. var len = this.rotation.lengthSquared();
  34677. if (len) {
  34678. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34679. }
  34680. }
  34681. if (!this.noRotationConstraint) {
  34682. var limit = (Math.PI / 2) * 0.95;
  34683. if (this.rotation.x > limit)
  34684. this.rotation.x = limit;
  34685. if (this.rotation.x < -limit)
  34686. this.rotation.x = -limit;
  34687. }
  34688. }
  34689. // Inertia
  34690. if (needToMove) {
  34691. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  34692. this.cameraDirection.x = 0;
  34693. }
  34694. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  34695. this.cameraDirection.y = 0;
  34696. }
  34697. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  34698. this.cameraDirection.z = 0;
  34699. }
  34700. this.cameraDirection.scaleInPlace(this.inertia);
  34701. }
  34702. if (needToRotate) {
  34703. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  34704. this.cameraRotation.x = 0;
  34705. }
  34706. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  34707. this.cameraRotation.y = 0;
  34708. }
  34709. this.cameraRotation.scaleInPlace(this.inertia);
  34710. }
  34711. _super.prototype._checkInputs.call(this);
  34712. };
  34713. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  34714. if (this.rotationQuaternion) {
  34715. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  34716. //update the up vector!
  34717. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  34718. }
  34719. else {
  34720. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  34721. }
  34722. };
  34723. TargetCamera.prototype._getViewMatrix = function () {
  34724. if (!this.lockedTarget) {
  34725. // Compute
  34726. this._updateCameraRotationMatrix();
  34727. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  34728. // Computing target and final matrix
  34729. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  34730. }
  34731. else {
  34732. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  34733. }
  34734. if (this.getScene().useRightHandedSystem) {
  34735. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34736. }
  34737. else {
  34738. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34739. }
  34740. return this._viewMatrix;
  34741. };
  34742. /**
  34743. * @override
  34744. * Override Camera.createRigCamera
  34745. */
  34746. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34747. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  34748. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  34749. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  34750. if (!this.rotationQuaternion) {
  34751. this.rotationQuaternion = new BABYLON.Quaternion();
  34752. }
  34753. rigCamera._cameraRigParams = {};
  34754. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  34755. }
  34756. return rigCamera;
  34757. }
  34758. return null;
  34759. };
  34760. /**
  34761. * @override
  34762. * Override Camera._updateRigCameras
  34763. */
  34764. TargetCamera.prototype._updateRigCameras = function () {
  34765. var camLeft = this._rigCameras[0];
  34766. var camRight = this._rigCameras[1];
  34767. switch (this.cameraRigMode) {
  34768. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34769. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34770. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34771. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34772. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  34773. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  34774. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  34775. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  34776. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  34777. camLeft.setTarget(this.getTarget());
  34778. camRight.setTarget(this.getTarget());
  34779. break;
  34780. case BABYLON.Camera.RIG_MODE_VR:
  34781. if (camLeft.rotationQuaternion) {
  34782. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34783. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34784. }
  34785. else {
  34786. camLeft.rotation.copyFrom(this.rotation);
  34787. camRight.rotation.copyFrom(this.rotation);
  34788. }
  34789. camLeft.position.copyFrom(this.position);
  34790. camRight.position.copyFrom(this.position);
  34791. break;
  34792. }
  34793. _super.prototype._updateRigCameras.call(this);
  34794. };
  34795. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  34796. if (!this._rigCamTransformMatrix) {
  34797. this._rigCamTransformMatrix = new BABYLON.Matrix();
  34798. }
  34799. var target = this.getTarget();
  34800. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  34801. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  34802. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  34803. };
  34804. TargetCamera.prototype.getClassName = function () {
  34805. return "TargetCamera";
  34806. };
  34807. __decorate([
  34808. BABYLON.serializeAsVector3()
  34809. ], TargetCamera.prototype, "rotation", void 0);
  34810. __decorate([
  34811. BABYLON.serialize()
  34812. ], TargetCamera.prototype, "speed", void 0);
  34813. __decorate([
  34814. BABYLON.serializeAsMeshReference("lockedTargetId")
  34815. ], TargetCamera.prototype, "lockedTarget", void 0);
  34816. return TargetCamera;
  34817. }(BABYLON.Camera));
  34818. BABYLON.TargetCamera = TargetCamera;
  34819. })(BABYLON || (BABYLON = {}));
  34820. //# sourceMappingURL=babylon.targetCamera.js.map
  34821. var BABYLON;
  34822. (function (BABYLON) {
  34823. var FreeCamera = (function (_super) {
  34824. __extends(FreeCamera, _super);
  34825. function FreeCamera(name, position, scene) {
  34826. var _this = _super.call(this, name, position, scene) || this;
  34827. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  34828. _this.checkCollisions = false;
  34829. _this.applyGravity = false;
  34830. _this._needMoveForGravity = false;
  34831. _this._oldPosition = BABYLON.Vector3.Zero();
  34832. _this._diffPosition = BABYLON.Vector3.Zero();
  34833. _this._newPosition = BABYLON.Vector3.Zero();
  34834. // Collisions
  34835. _this._collisionMask = -1;
  34836. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34837. if (collidedMesh === void 0) { collidedMesh = null; }
  34838. //TODO move this to the collision coordinator!
  34839. if (_this.getScene().workerCollisions)
  34840. newPosition.multiplyInPlace(_this._collider.radius);
  34841. var updatePosition = function (newPos) {
  34842. _this._newPosition.copyFrom(newPos);
  34843. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  34844. var oldPosition = _this.position.clone();
  34845. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  34846. _this.position.addInPlace(_this._diffPosition);
  34847. if (_this.onCollide && collidedMesh) {
  34848. _this.onCollide(collidedMesh);
  34849. }
  34850. }
  34851. };
  34852. updatePosition(newPosition);
  34853. };
  34854. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  34855. _this.inputs.addKeyboard().addMouse();
  34856. return _this;
  34857. }
  34858. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  34859. //-- begin properties for backward compatibility for inputs
  34860. get: function () {
  34861. var mouse = this.inputs.attached["mouse"];
  34862. if (mouse)
  34863. return mouse.angularSensibility;
  34864. },
  34865. set: function (value) {
  34866. var mouse = this.inputs.attached["mouse"];
  34867. if (mouse)
  34868. mouse.angularSensibility = value;
  34869. },
  34870. enumerable: true,
  34871. configurable: true
  34872. });
  34873. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  34874. get: function () {
  34875. var keyboard = this.inputs.attached["keyboard"];
  34876. if (keyboard)
  34877. return keyboard.keysUp;
  34878. },
  34879. set: function (value) {
  34880. var keyboard = this.inputs.attached["keyboard"];
  34881. if (keyboard)
  34882. keyboard.keysUp = value;
  34883. },
  34884. enumerable: true,
  34885. configurable: true
  34886. });
  34887. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  34888. get: function () {
  34889. var keyboard = this.inputs.attached["keyboard"];
  34890. if (keyboard)
  34891. return keyboard.keysDown;
  34892. },
  34893. set: function (value) {
  34894. var keyboard = this.inputs.attached["keyboard"];
  34895. if (keyboard)
  34896. keyboard.keysDown = value;
  34897. },
  34898. enumerable: true,
  34899. configurable: true
  34900. });
  34901. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  34902. get: function () {
  34903. var keyboard = this.inputs.attached["keyboard"];
  34904. if (keyboard)
  34905. return keyboard.keysLeft;
  34906. },
  34907. set: function (value) {
  34908. var keyboard = this.inputs.attached["keyboard"];
  34909. if (keyboard)
  34910. keyboard.keysLeft = value;
  34911. },
  34912. enumerable: true,
  34913. configurable: true
  34914. });
  34915. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  34916. get: function () {
  34917. var keyboard = this.inputs.attached["keyboard"];
  34918. if (keyboard)
  34919. return keyboard.keysRight;
  34920. },
  34921. set: function (value) {
  34922. var keyboard = this.inputs.attached["keyboard"];
  34923. if (keyboard)
  34924. keyboard.keysRight = value;
  34925. },
  34926. enumerable: true,
  34927. configurable: true
  34928. });
  34929. // Controls
  34930. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34931. this.inputs.attachElement(element, noPreventDefault);
  34932. };
  34933. FreeCamera.prototype.detachControl = function (element) {
  34934. this.inputs.detachElement(element);
  34935. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34936. this.cameraRotation = new BABYLON.Vector2(0, 0);
  34937. };
  34938. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  34939. get: function () {
  34940. return this._collisionMask;
  34941. },
  34942. set: function (mask) {
  34943. this._collisionMask = !isNaN(mask) ? mask : -1;
  34944. },
  34945. enumerable: true,
  34946. configurable: true
  34947. });
  34948. FreeCamera.prototype._collideWithWorld = function (displacement) {
  34949. var globalPosition;
  34950. if (this.parent) {
  34951. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  34952. }
  34953. else {
  34954. globalPosition = this.position;
  34955. }
  34956. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  34957. if (!this._collider) {
  34958. this._collider = new BABYLON.Collider();
  34959. }
  34960. this._collider.radius = this.ellipsoid;
  34961. this._collider.collisionMask = this._collisionMask;
  34962. //no need for clone, as long as gravity is not on.
  34963. var actualDisplacement = displacement;
  34964. //add gravity to the direction to prevent the dual-collision checking
  34965. if (this.applyGravity) {
  34966. //this prevents mending with cameraDirection, a global variable of the free camera class.
  34967. actualDisplacement = displacement.add(this.getScene().gravity);
  34968. }
  34969. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34970. };
  34971. FreeCamera.prototype._checkInputs = function () {
  34972. if (!this._localDirection) {
  34973. this._localDirection = BABYLON.Vector3.Zero();
  34974. this._transformedDirection = BABYLON.Vector3.Zero();
  34975. }
  34976. this.inputs.checkInputs();
  34977. _super.prototype._checkInputs.call(this);
  34978. };
  34979. FreeCamera.prototype._decideIfNeedsToMove = function () {
  34980. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34981. };
  34982. FreeCamera.prototype._updatePosition = function () {
  34983. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  34984. this._collideWithWorld(this.cameraDirection);
  34985. }
  34986. else {
  34987. _super.prototype._updatePosition.call(this);
  34988. }
  34989. };
  34990. FreeCamera.prototype.dispose = function () {
  34991. this.inputs.clear();
  34992. _super.prototype.dispose.call(this);
  34993. };
  34994. FreeCamera.prototype.getClassName = function () {
  34995. return "FreeCamera";
  34996. };
  34997. __decorate([
  34998. BABYLON.serializeAsVector3()
  34999. ], FreeCamera.prototype, "ellipsoid", void 0);
  35000. __decorate([
  35001. BABYLON.serialize()
  35002. ], FreeCamera.prototype, "checkCollisions", void 0);
  35003. __decorate([
  35004. BABYLON.serialize()
  35005. ], FreeCamera.prototype, "applyGravity", void 0);
  35006. return FreeCamera;
  35007. }(BABYLON.TargetCamera));
  35008. BABYLON.FreeCamera = FreeCamera;
  35009. })(BABYLON || (BABYLON = {}));
  35010. //# sourceMappingURL=babylon.freeCamera.js.map
  35011. var BABYLON;
  35012. (function (BABYLON) {
  35013. var ArcRotateCameraKeyboardMoveInput = (function () {
  35014. function ArcRotateCameraKeyboardMoveInput() {
  35015. this._keys = [];
  35016. this.keysUp = [38];
  35017. this.keysDown = [40];
  35018. this.keysLeft = [37];
  35019. this.keysRight = [39];
  35020. this.keysReset = [111];
  35021. this.panningSensibility = 50.0;
  35022. }
  35023. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  35024. var _this = this;
  35025. if (this._onCanvasBlurObserver) {
  35026. return;
  35027. }
  35028. this._scene = this.camera.getScene();
  35029. this._engine = this._scene.getEngine();
  35030. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  35031. _this._keys = [];
  35032. });
  35033. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  35034. var evt = info.event;
  35035. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  35036. _this._ctrlPressed = evt.ctrlKey;
  35037. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35038. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35039. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35040. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  35041. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  35042. var index = _this._keys.indexOf(evt.keyCode);
  35043. if (index === -1) {
  35044. _this._keys.push(evt.keyCode);
  35045. }
  35046. if (evt.preventDefault) {
  35047. if (!noPreventDefault) {
  35048. evt.preventDefault();
  35049. }
  35050. }
  35051. }
  35052. }
  35053. else {
  35054. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35055. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35056. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35057. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  35058. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  35059. var index = _this._keys.indexOf(evt.keyCode);
  35060. if (index >= 0) {
  35061. _this._keys.splice(index, 1);
  35062. }
  35063. if (evt.preventDefault) {
  35064. if (!noPreventDefault) {
  35065. evt.preventDefault();
  35066. }
  35067. }
  35068. }
  35069. }
  35070. });
  35071. };
  35072. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  35073. if (this._scene) {
  35074. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  35075. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  35076. this._onKeyboardObserver = null;
  35077. this._onCanvasBlurObserver = null;
  35078. }
  35079. this._keys = [];
  35080. };
  35081. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  35082. if (this._onKeyboardObserver) {
  35083. var camera = this.camera;
  35084. for (var index = 0; index < this._keys.length; index++) {
  35085. var keyCode = this._keys[index];
  35086. if (this.keysLeft.indexOf(keyCode) !== -1) {
  35087. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35088. camera.inertialPanningX -= 1 / this.panningSensibility;
  35089. }
  35090. else {
  35091. camera.inertialAlphaOffset -= 0.01;
  35092. }
  35093. }
  35094. else if (this.keysUp.indexOf(keyCode) !== -1) {
  35095. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35096. camera.inertialPanningY += 1 / this.panningSensibility;
  35097. }
  35098. else {
  35099. camera.inertialBetaOffset -= 0.01;
  35100. }
  35101. }
  35102. else if (this.keysRight.indexOf(keyCode) !== -1) {
  35103. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35104. camera.inertialPanningX += 1 / this.panningSensibility;
  35105. }
  35106. else {
  35107. camera.inertialAlphaOffset += 0.01;
  35108. }
  35109. }
  35110. else if (this.keysDown.indexOf(keyCode) !== -1) {
  35111. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35112. camera.inertialPanningY -= 1 / this.panningSensibility;
  35113. }
  35114. else {
  35115. camera.inertialBetaOffset += 0.01;
  35116. }
  35117. }
  35118. else if (this.keysReset.indexOf(keyCode) !== -1) {
  35119. camera.restoreState();
  35120. }
  35121. }
  35122. }
  35123. };
  35124. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  35125. return "ArcRotateCameraKeyboardMoveInput";
  35126. };
  35127. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  35128. return "keyboard";
  35129. };
  35130. __decorate([
  35131. BABYLON.serialize()
  35132. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  35133. __decorate([
  35134. BABYLON.serialize()
  35135. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  35136. __decorate([
  35137. BABYLON.serialize()
  35138. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  35139. __decorate([
  35140. BABYLON.serialize()
  35141. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  35142. __decorate([
  35143. BABYLON.serialize()
  35144. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  35145. __decorate([
  35146. BABYLON.serialize()
  35147. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  35148. return ArcRotateCameraKeyboardMoveInput;
  35149. }());
  35150. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  35151. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  35152. })(BABYLON || (BABYLON = {}));
  35153. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  35154. var BABYLON;
  35155. (function (BABYLON) {
  35156. var ArcRotateCameraMouseWheelInput = (function () {
  35157. function ArcRotateCameraMouseWheelInput() {
  35158. this.wheelPrecision = 3.0;
  35159. }
  35160. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  35161. var _this = this;
  35162. this._wheel = function (p, s) {
  35163. //sanity check - this should be a PointerWheel event.
  35164. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  35165. return;
  35166. var event = p.event;
  35167. var delta = 0;
  35168. if (event.wheelDelta) {
  35169. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  35170. }
  35171. else if (event.detail) {
  35172. delta = -event.detail / _this.wheelPrecision;
  35173. }
  35174. if (delta)
  35175. _this.camera.inertialRadiusOffset += delta;
  35176. if (event.preventDefault) {
  35177. if (!noPreventDefault) {
  35178. event.preventDefault();
  35179. }
  35180. }
  35181. };
  35182. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  35183. };
  35184. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  35185. if (this._observer && element) {
  35186. this.camera.getScene().onPointerObservable.remove(this._observer);
  35187. this._observer = null;
  35188. this._wheel = null;
  35189. }
  35190. };
  35191. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  35192. return "ArcRotateCameraMouseWheelInput";
  35193. };
  35194. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  35195. return "mousewheel";
  35196. };
  35197. __decorate([
  35198. BABYLON.serialize()
  35199. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  35200. return ArcRotateCameraMouseWheelInput;
  35201. }());
  35202. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  35203. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  35204. })(BABYLON || (BABYLON = {}));
  35205. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  35206. var BABYLON;
  35207. (function (BABYLON) {
  35208. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  35209. var ArcRotateCameraPointersInput = (function () {
  35210. function ArcRotateCameraPointersInput() {
  35211. this.buttons = [0, 1, 2];
  35212. this.angularSensibilityX = 1000.0;
  35213. this.angularSensibilityY = 1000.0;
  35214. this.pinchPrecision = 6.0;
  35215. this.panningSensibility = 50.0;
  35216. this.multiTouchPanning = true;
  35217. this._isPanClick = false;
  35218. this.pinchInwards = true;
  35219. }
  35220. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  35221. var _this = this;
  35222. var engine = this.camera.getEngine();
  35223. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  35224. var pointA, pointB;
  35225. var previousPinchSquaredDistance = 0;
  35226. var previousPinchDistance = 0;
  35227. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false };
  35228. this._pointerInput = function (p, s) {
  35229. var evt = p.event;
  35230. if (engine.isInVRExclusivePointerMode) {
  35231. return;
  35232. }
  35233. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  35234. return;
  35235. }
  35236. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  35237. try {
  35238. evt.srcElement.setPointerCapture(evt.pointerId);
  35239. }
  35240. catch (e) {
  35241. //Nothing to do with the error. Execution will continue.
  35242. }
  35243. // Manage panning with pan button click
  35244. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  35245. // manage pointers
  35246. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  35247. if (pointA === undefined) {
  35248. pointA = cacheSoloPointer;
  35249. }
  35250. else if (pointB === undefined) {
  35251. pointB = cacheSoloPointer;
  35252. }
  35253. if (!noPreventDefault) {
  35254. evt.preventDefault();
  35255. element.focus();
  35256. }
  35257. }
  35258. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  35259. _this.camera.restoreState();
  35260. }
  35261. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  35262. try {
  35263. evt.srcElement.releasePointerCapture(evt.pointerId);
  35264. }
  35265. catch (e) {
  35266. //Nothing to do with the error.
  35267. }
  35268. cacheSoloPointer = null;
  35269. previousPinchSquaredDistance = 0;
  35270. previousPinchDistance = 0;
  35271. previousMultiTouchPanPosition.isPaning = false;
  35272. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  35273. //but emptying completly pointers collection is required to fix a bug on iPhone :
  35274. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  35275. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  35276. pointA = pointB = undefined;
  35277. if (!noPreventDefault) {
  35278. evt.preventDefault();
  35279. }
  35280. }
  35281. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  35282. if (!noPreventDefault) {
  35283. evt.preventDefault();
  35284. }
  35285. // One button down
  35286. if (pointA && pointB === undefined) {
  35287. if (_this.panningSensibility !== 0 &&
  35288. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  35289. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  35290. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  35291. }
  35292. else {
  35293. var offsetX = evt.clientX - cacheSoloPointer.x;
  35294. var offsetY = evt.clientY - cacheSoloPointer.y;
  35295. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35296. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35297. }
  35298. cacheSoloPointer.x = evt.clientX;
  35299. cacheSoloPointer.y = evt.clientY;
  35300. }
  35301. else if (pointA && pointB) {
  35302. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  35303. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  35304. ed.x = evt.clientX;
  35305. ed.y = evt.clientY;
  35306. var direction = _this.pinchInwards ? 1 : -1;
  35307. var distX = pointA.x - pointB.x;
  35308. var distY = pointA.y - pointB.y;
  35309. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  35310. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  35311. if (previousPinchSquaredDistance === 0) {
  35312. previousPinchSquaredDistance = pinchSquaredDistance;
  35313. previousPinchDistance = pinchDistance;
  35314. return;
  35315. }
  35316. if (pinchDistance > _this.camera.panMaxFingersDistance || Math.abs(pinchDistance - previousPinchDistance) > _this.camera.pinchToPanMaxDistance) {
  35317. _this.camera
  35318. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  35319. (_this.pinchPrecision *
  35320. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  35321. direction);
  35322. previousMultiTouchPanPosition.isPaning = false;
  35323. }
  35324. else {
  35325. if (cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  35326. if (!previousMultiTouchPanPosition.isPaning) {
  35327. previousMultiTouchPanPosition.isPaning = true;
  35328. previousMultiTouchPanPosition.x = ed.x;
  35329. previousMultiTouchPanPosition.y = ed.y;
  35330. return;
  35331. }
  35332. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / _this.panningSensibility;
  35333. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / _this.panningSensibility;
  35334. }
  35335. }
  35336. if (cacheSoloPointer.pointerId === evt.pointerId) {
  35337. previousMultiTouchPanPosition.x = ed.x;
  35338. previousMultiTouchPanPosition.y = ed.y;
  35339. }
  35340. previousPinchSquaredDistance = pinchSquaredDistance;
  35341. previousPinchDistance = pinchDistance;
  35342. }
  35343. }
  35344. };
  35345. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  35346. this._onContextMenu = function (evt) {
  35347. evt.preventDefault();
  35348. };
  35349. if (!this.camera._useCtrlForPanning) {
  35350. element.addEventListener("contextmenu", this._onContextMenu, false);
  35351. }
  35352. this._onLostFocus = function () {
  35353. //this._keys = [];
  35354. pointA = pointB = undefined;
  35355. previousPinchSquaredDistance = 0;
  35356. previousPinchDistance = 0;
  35357. previousMultiTouchPanPosition.isPaning = false;
  35358. cacheSoloPointer = null;
  35359. };
  35360. this._onMouseMove = function (evt) {
  35361. if (!engine.isPointerLock) {
  35362. return;
  35363. }
  35364. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  35365. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  35366. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35367. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35368. if (!noPreventDefault) {
  35369. evt.preventDefault();
  35370. }
  35371. };
  35372. this._onGestureStart = function (e) {
  35373. if (window.MSGesture === undefined) {
  35374. return;
  35375. }
  35376. if (!_this._MSGestureHandler) {
  35377. _this._MSGestureHandler = new MSGesture();
  35378. _this._MSGestureHandler.target = element;
  35379. }
  35380. _this._MSGestureHandler.addPointer(e.pointerId);
  35381. };
  35382. this._onGesture = function (e) {
  35383. _this.camera.radius *= e.scale;
  35384. if (e.preventDefault) {
  35385. if (!noPreventDefault) {
  35386. e.stopPropagation();
  35387. e.preventDefault();
  35388. }
  35389. }
  35390. };
  35391. element.addEventListener("mousemove", this._onMouseMove, false);
  35392. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  35393. element.addEventListener("MSGestureChange", this._onGesture, false);
  35394. BABYLON.Tools.RegisterTopRootEvents([
  35395. { name: "blur", handler: this._onLostFocus }
  35396. ]);
  35397. };
  35398. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  35399. BABYLON.Tools.UnregisterTopRootEvents([
  35400. { name: "blur", handler: this._onLostFocus }
  35401. ]);
  35402. if (element && this._observer) {
  35403. this.camera.getScene().onPointerObservable.remove(this._observer);
  35404. this._observer = null;
  35405. element.removeEventListener("contextmenu", this._onContextMenu);
  35406. element.removeEventListener("mousemove", this._onMouseMove);
  35407. element.removeEventListener("MSPointerDown", this._onGestureStart);
  35408. element.removeEventListener("MSGestureChange", this._onGesture);
  35409. this._isPanClick = false;
  35410. this.pinchInwards = true;
  35411. this._onMouseMove = null;
  35412. this._onGestureStart = null;
  35413. this._onGesture = null;
  35414. this._MSGestureHandler = null;
  35415. this._onLostFocus = null;
  35416. this._onContextMenu = null;
  35417. }
  35418. };
  35419. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  35420. return "ArcRotateCameraPointersInput";
  35421. };
  35422. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  35423. return "pointers";
  35424. };
  35425. __decorate([
  35426. BABYLON.serialize()
  35427. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  35428. __decorate([
  35429. BABYLON.serialize()
  35430. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  35431. __decorate([
  35432. BABYLON.serialize()
  35433. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  35434. __decorate([
  35435. BABYLON.serialize()
  35436. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  35437. __decorate([
  35438. BABYLON.serialize()
  35439. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  35440. __decorate([
  35441. BABYLON.serialize()
  35442. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  35443. return ArcRotateCameraPointersInput;
  35444. }());
  35445. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  35446. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  35447. })(BABYLON || (BABYLON = {}));
  35448. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  35449. /// <reference path="babylon.targetCamera.ts" />
  35450. /// <reference path="..\Tools\babylon.tools.ts" />
  35451. var BABYLON;
  35452. (function (BABYLON) {
  35453. var ArcRotateCamera = (function (_super) {
  35454. __extends(ArcRotateCamera, _super);
  35455. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  35456. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  35457. _this.inertialAlphaOffset = 0;
  35458. _this.inertialBetaOffset = 0;
  35459. _this.inertialRadiusOffset = 0;
  35460. _this.lowerAlphaLimit = null;
  35461. _this.upperAlphaLimit = null;
  35462. _this.lowerBetaLimit = 0.01;
  35463. _this.upperBetaLimit = Math.PI;
  35464. _this.lowerRadiusLimit = null;
  35465. _this.upperRadiusLimit = null;
  35466. _this.inertialPanningX = 0;
  35467. _this.inertialPanningY = 0;
  35468. _this.pinchToPanMaxDistance = 3;
  35469. _this.panMaxFingersDistance = 100;
  35470. _this.panningDistanceLimit = null;
  35471. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  35472. _this.panningInertia = 0.9;
  35473. //-- end properties for backward compatibility for inputs
  35474. _this.zoomOnFactor = 1;
  35475. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  35476. _this.allowUpsideDown = true;
  35477. _this._viewMatrix = new BABYLON.Matrix();
  35478. // Panning
  35479. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  35480. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  35481. _this.checkCollisions = false;
  35482. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35483. _this._previousPosition = BABYLON.Vector3.Zero();
  35484. _this._collisionVelocity = BABYLON.Vector3.Zero();
  35485. _this._newPosition = BABYLON.Vector3.Zero();
  35486. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  35487. if (collidedMesh === void 0) { collidedMesh = null; }
  35488. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  35489. newPosition.multiplyInPlace(_this._collider.radius);
  35490. }
  35491. if (!collidedMesh) {
  35492. _this._previousPosition.copyFrom(_this.position);
  35493. }
  35494. else {
  35495. _this.setPosition(newPosition);
  35496. if (_this.onCollide) {
  35497. _this.onCollide(collidedMesh);
  35498. }
  35499. }
  35500. // Recompute because of constraints
  35501. var cosa = Math.cos(_this.alpha);
  35502. var sina = Math.sin(_this.alpha);
  35503. var cosb = Math.cos(_this.beta);
  35504. var sinb = Math.sin(_this.beta);
  35505. if (sinb === 0) {
  35506. sinb = 0.0001;
  35507. }
  35508. var target = _this._getTargetPosition();
  35509. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  35510. _this.position.copyFrom(_this._newPosition);
  35511. var up = _this.upVector;
  35512. if (_this.allowUpsideDown && _this.beta < 0) {
  35513. up = up.clone();
  35514. up = up.negate();
  35515. }
  35516. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  35517. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  35518. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  35519. _this._collisionTriggered = false;
  35520. };
  35521. _this._target = BABYLON.Vector3.Zero();
  35522. if (target) {
  35523. _this.setTarget(target);
  35524. }
  35525. _this.alpha = alpha;
  35526. _this.beta = beta;
  35527. _this.radius = radius;
  35528. _this.getViewMatrix();
  35529. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  35530. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  35531. return _this;
  35532. }
  35533. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  35534. get: function () {
  35535. return this._target;
  35536. },
  35537. set: function (value) {
  35538. this.setTarget(value);
  35539. },
  35540. enumerable: true,
  35541. configurable: true
  35542. });
  35543. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  35544. //-- begin properties for backward compatibility for inputs
  35545. get: function () {
  35546. var pointers = this.inputs.attached["pointers"];
  35547. if (pointers)
  35548. return pointers.angularSensibilityX;
  35549. },
  35550. set: function (value) {
  35551. var pointers = this.inputs.attached["pointers"];
  35552. if (pointers) {
  35553. pointers.angularSensibilityX = value;
  35554. }
  35555. },
  35556. enumerable: true,
  35557. configurable: true
  35558. });
  35559. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  35560. get: function () {
  35561. var pointers = this.inputs.attached["pointers"];
  35562. if (pointers)
  35563. return pointers.angularSensibilityY;
  35564. },
  35565. set: function (value) {
  35566. var pointers = this.inputs.attached["pointers"];
  35567. if (pointers) {
  35568. pointers.angularSensibilityY = value;
  35569. }
  35570. },
  35571. enumerable: true,
  35572. configurable: true
  35573. });
  35574. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  35575. get: function () {
  35576. var pointers = this.inputs.attached["pointers"];
  35577. if (pointers)
  35578. return pointers.pinchPrecision;
  35579. },
  35580. set: function (value) {
  35581. var pointers = this.inputs.attached["pointers"];
  35582. if (pointers) {
  35583. pointers.pinchPrecision = value;
  35584. }
  35585. },
  35586. enumerable: true,
  35587. configurable: true
  35588. });
  35589. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  35590. get: function () {
  35591. var pointers = this.inputs.attached["pointers"];
  35592. if (pointers)
  35593. return pointers.panningSensibility;
  35594. },
  35595. set: function (value) {
  35596. var pointers = this.inputs.attached["pointers"];
  35597. if (pointers) {
  35598. pointers.panningSensibility = value;
  35599. }
  35600. },
  35601. enumerable: true,
  35602. configurable: true
  35603. });
  35604. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  35605. get: function () {
  35606. var keyboard = this.inputs.attached["keyboard"];
  35607. if (keyboard)
  35608. return keyboard.keysUp;
  35609. },
  35610. set: function (value) {
  35611. var keyboard = this.inputs.attached["keyboard"];
  35612. if (keyboard)
  35613. keyboard.keysUp = value;
  35614. },
  35615. enumerable: true,
  35616. configurable: true
  35617. });
  35618. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  35619. get: function () {
  35620. var keyboard = this.inputs.attached["keyboard"];
  35621. if (keyboard)
  35622. return keyboard.keysDown;
  35623. },
  35624. set: function (value) {
  35625. var keyboard = this.inputs.attached["keyboard"];
  35626. if (keyboard)
  35627. keyboard.keysDown = value;
  35628. },
  35629. enumerable: true,
  35630. configurable: true
  35631. });
  35632. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  35633. get: function () {
  35634. var keyboard = this.inputs.attached["keyboard"];
  35635. if (keyboard)
  35636. return keyboard.keysLeft;
  35637. },
  35638. set: function (value) {
  35639. var keyboard = this.inputs.attached["keyboard"];
  35640. if (keyboard)
  35641. keyboard.keysLeft = value;
  35642. },
  35643. enumerable: true,
  35644. configurable: true
  35645. });
  35646. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  35647. get: function () {
  35648. var keyboard = this.inputs.attached["keyboard"];
  35649. if (keyboard)
  35650. return keyboard.keysRight;
  35651. },
  35652. set: function (value) {
  35653. var keyboard = this.inputs.attached["keyboard"];
  35654. if (keyboard)
  35655. keyboard.keysRight = value;
  35656. },
  35657. enumerable: true,
  35658. configurable: true
  35659. });
  35660. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  35661. get: function () {
  35662. var mousewheel = this.inputs.attached["mousewheel"];
  35663. if (mousewheel)
  35664. return mousewheel.wheelPrecision;
  35665. },
  35666. set: function (value) {
  35667. var mousewheel = this.inputs.attached["mousewheel"];
  35668. if (mousewheel)
  35669. mousewheel.wheelPrecision = value;
  35670. },
  35671. enumerable: true,
  35672. configurable: true
  35673. });
  35674. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  35675. get: function () {
  35676. return this._bouncingBehavior;
  35677. },
  35678. enumerable: true,
  35679. configurable: true
  35680. });
  35681. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  35682. get: function () {
  35683. return this._bouncingBehavior != null;
  35684. },
  35685. set: function (value) {
  35686. if (value === this.useBouncingBehavior) {
  35687. return;
  35688. }
  35689. if (value) {
  35690. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  35691. this.addBehavior(this._bouncingBehavior);
  35692. }
  35693. else {
  35694. this.removeBehavior(this._bouncingBehavior);
  35695. this._bouncingBehavior = null;
  35696. }
  35697. },
  35698. enumerable: true,
  35699. configurable: true
  35700. });
  35701. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  35702. get: function () {
  35703. return this._framingBehavior;
  35704. },
  35705. enumerable: true,
  35706. configurable: true
  35707. });
  35708. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  35709. get: function () {
  35710. return this._framingBehavior != null;
  35711. },
  35712. set: function (value) {
  35713. if (value === this.useFramingBehavior) {
  35714. return;
  35715. }
  35716. if (value) {
  35717. this._framingBehavior = new BABYLON.FramingBehavior();
  35718. this.addBehavior(this._framingBehavior);
  35719. }
  35720. else {
  35721. this.removeBehavior(this._framingBehavior);
  35722. this._framingBehavior = null;
  35723. }
  35724. },
  35725. enumerable: true,
  35726. configurable: true
  35727. });
  35728. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  35729. get: function () {
  35730. return this._autoRotationBehavior;
  35731. },
  35732. enumerable: true,
  35733. configurable: true
  35734. });
  35735. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  35736. get: function () {
  35737. return this._autoRotationBehavior != null;
  35738. },
  35739. set: function (value) {
  35740. if (value === this.useAutoRotationBehavior) {
  35741. return;
  35742. }
  35743. if (value) {
  35744. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  35745. this.addBehavior(this._autoRotationBehavior);
  35746. }
  35747. else {
  35748. this.removeBehavior(this._autoRotationBehavior);
  35749. this._autoRotationBehavior = null;
  35750. }
  35751. },
  35752. enumerable: true,
  35753. configurable: true
  35754. });
  35755. // Cache
  35756. ArcRotateCamera.prototype._initCache = function () {
  35757. _super.prototype._initCache.call(this);
  35758. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  35759. this._cache.alpha = undefined;
  35760. this._cache.beta = undefined;
  35761. this._cache.radius = undefined;
  35762. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  35763. };
  35764. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  35765. if (!ignoreParentClass) {
  35766. _super.prototype._updateCache.call(this);
  35767. }
  35768. this._cache._target.copyFrom(this._getTargetPosition());
  35769. this._cache.alpha = this.alpha;
  35770. this._cache.beta = this.beta;
  35771. this._cache.radius = this.radius;
  35772. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  35773. };
  35774. ArcRotateCamera.prototype._getTargetPosition = function () {
  35775. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  35776. var pos = this._targetHost.getAbsolutePosition();
  35777. if (this._targetBoundingCenter) {
  35778. pos.addToRef(this._targetBoundingCenter, this._target);
  35779. }
  35780. else {
  35781. this._target.copyFrom(pos);
  35782. }
  35783. }
  35784. var lockedTargetPosition = this._getLockedTargetPosition();
  35785. if (lockedTargetPosition) {
  35786. return lockedTargetPosition;
  35787. }
  35788. return this._target;
  35789. };
  35790. ArcRotateCamera.prototype.storeState = function () {
  35791. this._storedAlpha = this.alpha;
  35792. this._storedBeta = this.beta;
  35793. this._storedRadius = this.radius;
  35794. this._storedTarget = this._getTargetPosition().clone();
  35795. return _super.prototype.storeState.call(this);
  35796. };
  35797. /**
  35798. * Restored camera state. You must call storeState() first
  35799. */
  35800. ArcRotateCamera.prototype._restoreStateValues = function () {
  35801. if (!_super.prototype._restoreStateValues.call(this)) {
  35802. return false;
  35803. }
  35804. this.alpha = this._storedAlpha;
  35805. this.beta = this._storedBeta;
  35806. this.radius = this._storedRadius;
  35807. this.setTarget(this._storedTarget);
  35808. this.inertialAlphaOffset = 0;
  35809. this.inertialBetaOffset = 0;
  35810. this.inertialRadiusOffset = 0;
  35811. this.inertialPanningX = 0;
  35812. this.inertialPanningY = 0;
  35813. return true;
  35814. };
  35815. // Synchronized
  35816. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  35817. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  35818. return false;
  35819. return this._cache._target.equals(this._getTargetPosition())
  35820. && this._cache.alpha === this.alpha
  35821. && this._cache.beta === this.beta
  35822. && this._cache.radius === this.radius
  35823. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  35824. };
  35825. // Methods
  35826. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  35827. var _this = this;
  35828. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  35829. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  35830. this._useCtrlForPanning = useCtrlForPanning;
  35831. this._panningMouseButton = panningMouseButton;
  35832. this.inputs.attachElement(element, noPreventDefault);
  35833. this._reset = function () {
  35834. _this.inertialAlphaOffset = 0;
  35835. _this.inertialBetaOffset = 0;
  35836. _this.inertialRadiusOffset = 0;
  35837. _this.inertialPanningX = 0;
  35838. _this.inertialPanningY = 0;
  35839. };
  35840. };
  35841. ArcRotateCamera.prototype.detachControl = function (element) {
  35842. this.inputs.detachElement(element);
  35843. if (this._reset) {
  35844. this._reset();
  35845. }
  35846. };
  35847. ArcRotateCamera.prototype._checkInputs = function () {
  35848. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  35849. if (this._collisionTriggered) {
  35850. return;
  35851. }
  35852. this.inputs.checkInputs();
  35853. // Inertia
  35854. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  35855. if (this.getScene().useRightHandedSystem) {
  35856. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35857. }
  35858. else {
  35859. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35860. }
  35861. this.beta += this.inertialBetaOffset;
  35862. this.radius -= this.inertialRadiusOffset;
  35863. this.inertialAlphaOffset *= this.inertia;
  35864. this.inertialBetaOffset *= this.inertia;
  35865. this.inertialRadiusOffset *= this.inertia;
  35866. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  35867. this.inertialAlphaOffset = 0;
  35868. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  35869. this.inertialBetaOffset = 0;
  35870. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  35871. this.inertialRadiusOffset = 0;
  35872. }
  35873. // Panning inertia
  35874. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  35875. if (!this._localDirection) {
  35876. this._localDirection = BABYLON.Vector3.Zero();
  35877. this._transformedDirection = BABYLON.Vector3.Zero();
  35878. }
  35879. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  35880. this._localDirection.multiplyInPlace(this.panningAxis);
  35881. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  35882. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  35883. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  35884. if (!this.panningAxis.y) {
  35885. this._transformedDirection.y = 0;
  35886. }
  35887. if (!this._targetHost) {
  35888. if (this.panningDistanceLimit) {
  35889. this._transformedDirection.addInPlace(this._target);
  35890. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  35891. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  35892. this._target.copyFrom(this._transformedDirection);
  35893. }
  35894. }
  35895. else {
  35896. this._target.addInPlace(this._transformedDirection);
  35897. }
  35898. }
  35899. this.inertialPanningX *= this.panningInertia;
  35900. this.inertialPanningY *= this.panningInertia;
  35901. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  35902. this.inertialPanningX = 0;
  35903. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  35904. this.inertialPanningY = 0;
  35905. }
  35906. // Limits
  35907. this._checkLimits();
  35908. _super.prototype._checkInputs.call(this);
  35909. };
  35910. ArcRotateCamera.prototype._checkLimits = function () {
  35911. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  35912. if (this.allowUpsideDown && this.beta > Math.PI) {
  35913. this.beta = this.beta - (2 * Math.PI);
  35914. }
  35915. }
  35916. else {
  35917. if (this.beta < this.lowerBetaLimit) {
  35918. this.beta = this.lowerBetaLimit;
  35919. }
  35920. }
  35921. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  35922. if (this.allowUpsideDown && this.beta < -Math.PI) {
  35923. this.beta = this.beta + (2 * Math.PI);
  35924. }
  35925. }
  35926. else {
  35927. if (this.beta > this.upperBetaLimit) {
  35928. this.beta = this.upperBetaLimit;
  35929. }
  35930. }
  35931. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  35932. this.alpha = this.lowerAlphaLimit;
  35933. }
  35934. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  35935. this.alpha = this.upperAlphaLimit;
  35936. }
  35937. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  35938. this.radius = this.lowerRadiusLimit;
  35939. }
  35940. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  35941. this.radius = this.upperRadiusLimit;
  35942. }
  35943. };
  35944. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  35945. var radiusv3 = this.position.subtract(this._getTargetPosition());
  35946. this.radius = radiusv3.length();
  35947. if (this.radius === 0) {
  35948. this.radius = 0.0001; // Just to avoid division by zero
  35949. }
  35950. // Alpha
  35951. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  35952. if (radiusv3.z < 0) {
  35953. this.alpha = 2 * Math.PI - this.alpha;
  35954. }
  35955. // Beta
  35956. this.beta = Math.acos(radiusv3.y / this.radius);
  35957. this._checkLimits();
  35958. };
  35959. ArcRotateCamera.prototype.setPosition = function (position) {
  35960. if (this.position.equals(position)) {
  35961. return;
  35962. }
  35963. this.position.copyFrom(position);
  35964. this.rebuildAnglesAndRadius();
  35965. };
  35966. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  35967. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  35968. if (allowSamePosition === void 0) { allowSamePosition = false; }
  35969. if (target.getBoundingInfo) {
  35970. if (toBoundingCenter) {
  35971. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  35972. }
  35973. else {
  35974. this._targetBoundingCenter = null;
  35975. }
  35976. this._targetHost = target;
  35977. this._target = this._getTargetPosition();
  35978. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  35979. }
  35980. else {
  35981. var newTarget = target;
  35982. var currentTarget = this._getTargetPosition();
  35983. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  35984. return;
  35985. }
  35986. this._targetHost = null;
  35987. this._target = newTarget;
  35988. this._targetBoundingCenter = null;
  35989. this.onMeshTargetChangedObservable.notifyObservers(null);
  35990. }
  35991. this.rebuildAnglesAndRadius();
  35992. };
  35993. ArcRotateCamera.prototype._getViewMatrix = function () {
  35994. // Compute
  35995. var cosa = Math.cos(this.alpha);
  35996. var sina = Math.sin(this.alpha);
  35997. var cosb = Math.cos(this.beta);
  35998. var sinb = Math.sin(this.beta);
  35999. if (sinb === 0) {
  36000. sinb = 0.0001;
  36001. }
  36002. var target = this._getTargetPosition();
  36003. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  36004. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  36005. if (!this._collider) {
  36006. this._collider = new BABYLON.Collider();
  36007. }
  36008. this._collider.radius = this.collisionRadius;
  36009. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  36010. this._collisionTriggered = true;
  36011. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  36012. }
  36013. else {
  36014. this.position.copyFrom(this._newPosition);
  36015. var up = this.upVector;
  36016. if (this.allowUpsideDown && sinb < 0) {
  36017. up = up.clone();
  36018. up = up.negate();
  36019. }
  36020. if (this.getScene().useRightHandedSystem) {
  36021. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  36022. }
  36023. else {
  36024. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  36025. }
  36026. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  36027. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  36028. }
  36029. this._currentTarget = target;
  36030. return this._viewMatrix;
  36031. };
  36032. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  36033. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  36034. meshes = meshes || this.getScene().meshes;
  36035. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  36036. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  36037. this.radius = distance * this.zoomOnFactor;
  36038. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  36039. };
  36040. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  36041. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  36042. var meshesOrMinMaxVector;
  36043. var distance;
  36044. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  36045. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  36046. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  36047. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  36048. }
  36049. else {
  36050. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  36051. distance = meshesOrMinMaxVectorAndDistance.distance;
  36052. }
  36053. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  36054. if (!doNotUpdateMaxZ) {
  36055. this.maxZ = distance * 2;
  36056. }
  36057. };
  36058. /**
  36059. * @override
  36060. * Override Camera.createRigCamera
  36061. */
  36062. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  36063. var alphaShift;
  36064. switch (this.cameraRigMode) {
  36065. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36066. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36067. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36068. case BABYLON.Camera.RIG_MODE_VR:
  36069. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  36070. break;
  36071. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36072. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  36073. break;
  36074. }
  36075. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  36076. rigCam._cameraRigParams = {};
  36077. return rigCam;
  36078. };
  36079. /**
  36080. * @override
  36081. * Override Camera._updateRigCameras
  36082. */
  36083. ArcRotateCamera.prototype._updateRigCameras = function () {
  36084. var camLeft = this._rigCameras[0];
  36085. var camRight = this._rigCameras[1];
  36086. camLeft.beta = camRight.beta = this.beta;
  36087. camLeft.radius = camRight.radius = this.radius;
  36088. switch (this.cameraRigMode) {
  36089. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36090. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36091. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36092. case BABYLON.Camera.RIG_MODE_VR:
  36093. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  36094. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  36095. break;
  36096. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36097. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  36098. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  36099. break;
  36100. }
  36101. _super.prototype._updateRigCameras.call(this);
  36102. };
  36103. ArcRotateCamera.prototype.dispose = function () {
  36104. this.inputs.clear();
  36105. _super.prototype.dispose.call(this);
  36106. };
  36107. ArcRotateCamera.prototype.getClassName = function () {
  36108. return "ArcRotateCamera";
  36109. };
  36110. __decorate([
  36111. BABYLON.serialize()
  36112. ], ArcRotateCamera.prototype, "alpha", void 0);
  36113. __decorate([
  36114. BABYLON.serialize()
  36115. ], ArcRotateCamera.prototype, "beta", void 0);
  36116. __decorate([
  36117. BABYLON.serialize()
  36118. ], ArcRotateCamera.prototype, "radius", void 0);
  36119. __decorate([
  36120. BABYLON.serializeAsVector3("target")
  36121. ], ArcRotateCamera.prototype, "_target", void 0);
  36122. __decorate([
  36123. BABYLON.serialize()
  36124. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  36125. __decorate([
  36126. BABYLON.serialize()
  36127. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  36128. __decorate([
  36129. BABYLON.serialize()
  36130. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  36131. __decorate([
  36132. BABYLON.serialize()
  36133. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  36134. __decorate([
  36135. BABYLON.serialize()
  36136. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  36137. __decorate([
  36138. BABYLON.serialize()
  36139. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  36140. __decorate([
  36141. BABYLON.serialize()
  36142. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  36143. __decorate([
  36144. BABYLON.serialize()
  36145. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  36146. __decorate([
  36147. BABYLON.serialize()
  36148. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  36149. __decorate([
  36150. BABYLON.serialize()
  36151. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  36152. __decorate([
  36153. BABYLON.serialize()
  36154. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  36155. __decorate([
  36156. BABYLON.serialize()
  36157. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  36158. __decorate([
  36159. BABYLON.serialize()
  36160. ], ArcRotateCamera.prototype, "panMaxFingersDistance", void 0);
  36161. __decorate([
  36162. BABYLON.serialize()
  36163. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  36164. __decorate([
  36165. BABYLON.serializeAsVector3()
  36166. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  36167. __decorate([
  36168. BABYLON.serialize()
  36169. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  36170. __decorate([
  36171. BABYLON.serialize()
  36172. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  36173. __decorate([
  36174. BABYLON.serialize()
  36175. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  36176. return ArcRotateCamera;
  36177. }(BABYLON.TargetCamera));
  36178. BABYLON.ArcRotateCamera = ArcRotateCamera;
  36179. })(BABYLON || (BABYLON = {}));
  36180. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  36181. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  36182. var BABYLON;
  36183. (function (BABYLON) {
  36184. var ArcRotateCameraInputsManager = (function (_super) {
  36185. __extends(ArcRotateCameraInputsManager, _super);
  36186. function ArcRotateCameraInputsManager(camera) {
  36187. return _super.call(this, camera) || this;
  36188. }
  36189. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  36190. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  36191. return this;
  36192. };
  36193. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  36194. this.add(new BABYLON.ArcRotateCameraPointersInput());
  36195. return this;
  36196. };
  36197. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  36198. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  36199. return this;
  36200. };
  36201. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  36202. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  36203. return this;
  36204. };
  36205. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  36206. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  36207. return this;
  36208. };
  36209. return ArcRotateCameraInputsManager;
  36210. }(BABYLON.CameraInputsManager));
  36211. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  36212. })(BABYLON || (BABYLON = {}));
  36213. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  36214. var BABYLON;
  36215. (function (BABYLON) {
  36216. var HemisphericLight = (function (_super) {
  36217. __extends(HemisphericLight, _super);
  36218. /**
  36219. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  36220. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  36221. * The HemisphericLight can't cast shadows.
  36222. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36223. */
  36224. function HemisphericLight(name, direction, scene) {
  36225. var _this = _super.call(this, name, scene) || this;
  36226. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  36227. _this.direction = direction || BABYLON.Vector3.Up();
  36228. return _this;
  36229. }
  36230. HemisphericLight.prototype._buildUniformLayout = function () {
  36231. this._uniformBuffer.addUniform("vLightData", 4);
  36232. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36233. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36234. this._uniformBuffer.addUniform("vLightGround", 3);
  36235. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36236. this._uniformBuffer.addUniform("depthValues", 2);
  36237. this._uniformBuffer.create();
  36238. };
  36239. /**
  36240. * Returns the string "HemisphericLight".
  36241. */
  36242. HemisphericLight.prototype.getClassName = function () {
  36243. return "HemisphericLight";
  36244. };
  36245. /**
  36246. * Sets the HemisphericLight direction towards the passed target (Vector3).
  36247. * Returns the updated direction.
  36248. */
  36249. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  36250. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  36251. return this.direction;
  36252. };
  36253. HemisphericLight.prototype.getShadowGenerator = function () {
  36254. return null;
  36255. };
  36256. /**
  36257. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  36258. * Returns the HemisphericLight.
  36259. */
  36260. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  36261. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36262. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  36263. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  36264. return this;
  36265. };
  36266. HemisphericLight.prototype._getWorldMatrix = function () {
  36267. if (!this._worldMatrix) {
  36268. this._worldMatrix = BABYLON.Matrix.Identity();
  36269. }
  36270. return this._worldMatrix;
  36271. };
  36272. /**
  36273. * Returns the integer 3.
  36274. */
  36275. HemisphericLight.prototype.getTypeID = function () {
  36276. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  36277. };
  36278. __decorate([
  36279. BABYLON.serializeAsColor3()
  36280. ], HemisphericLight.prototype, "groundColor", void 0);
  36281. __decorate([
  36282. BABYLON.serializeAsVector3()
  36283. ], HemisphericLight.prototype, "direction", void 0);
  36284. return HemisphericLight;
  36285. }(BABYLON.Light));
  36286. BABYLON.HemisphericLight = HemisphericLight;
  36287. })(BABYLON || (BABYLON = {}));
  36288. //# sourceMappingURL=babylon.hemisphericLight.js.map
  36289. var BABYLON;
  36290. (function (BABYLON) {
  36291. var ShadowLight = (function (_super) {
  36292. __extends(ShadowLight, _super);
  36293. function ShadowLight() {
  36294. var _this = _super !== null && _super.apply(this, arguments) || this;
  36295. _this._needProjectionMatrixCompute = true;
  36296. return _this;
  36297. }
  36298. Object.defineProperty(ShadowLight.prototype, "direction", {
  36299. get: function () {
  36300. return this._direction;
  36301. },
  36302. set: function (value) {
  36303. this._direction = value;
  36304. },
  36305. enumerable: true,
  36306. configurable: true
  36307. });
  36308. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36309. get: function () {
  36310. return this._shadowMinZ;
  36311. },
  36312. set: function (value) {
  36313. this._shadowMinZ = value;
  36314. this.forceProjectionMatrixCompute();
  36315. },
  36316. enumerable: true,
  36317. configurable: true
  36318. });
  36319. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36320. get: function () {
  36321. return this._shadowMaxZ;
  36322. },
  36323. set: function (value) {
  36324. this._shadowMaxZ = value;
  36325. this.forceProjectionMatrixCompute();
  36326. },
  36327. enumerable: true,
  36328. configurable: true
  36329. });
  36330. /**
  36331. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36332. */
  36333. ShadowLight.prototype.computeTransformedInformation = function () {
  36334. if (this.parent && this.parent.getWorldMatrix) {
  36335. if (!this.transformedPosition) {
  36336. this.transformedPosition = BABYLON.Vector3.Zero();
  36337. }
  36338. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36339. // In case the direction is present.
  36340. if (this.direction) {
  36341. if (!this.transformedDirection) {
  36342. this.transformedDirection = BABYLON.Vector3.Zero();
  36343. }
  36344. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36345. }
  36346. return true;
  36347. }
  36348. return false;
  36349. };
  36350. /**
  36351. * Return the depth scale used for the shadow map.
  36352. */
  36353. ShadowLight.prototype.getDepthScale = function () {
  36354. return 50.0;
  36355. };
  36356. /**
  36357. * Returns the light direction (Vector3) for any passed face index.
  36358. */
  36359. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36360. return this.transformedDirection ? this.transformedDirection : this.direction;
  36361. };
  36362. /**
  36363. * Returns the DirectionalLight absolute position in the World.
  36364. */
  36365. ShadowLight.prototype.getAbsolutePosition = function () {
  36366. return this.transformedPosition ? this.transformedPosition : this.position;
  36367. };
  36368. /**
  36369. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36370. * Returns the updated DirectionalLight direction (Vector3).
  36371. */
  36372. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36373. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36374. return this.direction;
  36375. };
  36376. /**
  36377. * Returns the light rotation (Vector3).
  36378. */
  36379. ShadowLight.prototype.getRotation = function () {
  36380. this.direction.normalize();
  36381. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36382. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36383. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36384. };
  36385. /**
  36386. * Boolean : false by default.
  36387. */
  36388. ShadowLight.prototype.needCube = function () {
  36389. return false;
  36390. };
  36391. /**
  36392. * Specifies wether or not the projection matrix should be recomputed this frame.
  36393. */
  36394. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36395. return this._needProjectionMatrixCompute;
  36396. };
  36397. /**
  36398. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36399. */
  36400. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36401. this._needProjectionMatrixCompute = true;
  36402. };
  36403. /**
  36404. * Get the world matrix of the sahdow lights.
  36405. */
  36406. ShadowLight.prototype._getWorldMatrix = function () {
  36407. if (!this._worldMatrix) {
  36408. this._worldMatrix = BABYLON.Matrix.Identity();
  36409. }
  36410. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36411. return this._worldMatrix;
  36412. };
  36413. /**
  36414. * Gets the minZ used for shadow according to both the scene and the light.
  36415. * @param activeCamera
  36416. */
  36417. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36418. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36419. };
  36420. /**
  36421. * Gets the maxZ used for shadow according to both the scene and the light.
  36422. * @param activeCamera
  36423. */
  36424. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36425. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36426. };
  36427. /**
  36428. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36429. * Returns the light.
  36430. */
  36431. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36432. if (this.customProjectionMatrixBuilder) {
  36433. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36434. }
  36435. else {
  36436. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36437. }
  36438. return this;
  36439. };
  36440. __decorate([
  36441. BABYLON.serializeAsVector3()
  36442. ], ShadowLight.prototype, "position", void 0);
  36443. __decorate([
  36444. BABYLON.serializeAsVector3()
  36445. ], ShadowLight.prototype, "direction", null);
  36446. __decorate([
  36447. BABYLON.serialize()
  36448. ], ShadowLight.prototype, "shadowMinZ", null);
  36449. __decorate([
  36450. BABYLON.serialize()
  36451. ], ShadowLight.prototype, "shadowMaxZ", null);
  36452. return ShadowLight;
  36453. }(BABYLON.Light));
  36454. BABYLON.ShadowLight = ShadowLight;
  36455. })(BABYLON || (BABYLON = {}));
  36456. //# sourceMappingURL=babylon.shadowLight.js.map
  36457. var BABYLON;
  36458. (function (BABYLON) {
  36459. var PointLight = (function (_super) {
  36460. __extends(PointLight, _super);
  36461. /**
  36462. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36463. * A PointLight emits the light in every direction.
  36464. * It can cast shadows.
  36465. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36466. * ```javascript
  36467. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36468. * ```
  36469. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36470. */
  36471. function PointLight(name, position, scene) {
  36472. var _this = _super.call(this, name, scene) || this;
  36473. _this._shadowAngle = Math.PI / 2;
  36474. _this.position = position;
  36475. return _this;
  36476. }
  36477. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36478. /**
  36479. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36480. * This specifies what angle the shadow will use to be created.
  36481. *
  36482. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36483. */
  36484. get: function () {
  36485. return this._shadowAngle;
  36486. },
  36487. /**
  36488. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36489. * This specifies what angle the shadow will use to be created.
  36490. *
  36491. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36492. */
  36493. set: function (value) {
  36494. this._shadowAngle = value;
  36495. this.forceProjectionMatrixCompute();
  36496. },
  36497. enumerable: true,
  36498. configurable: true
  36499. });
  36500. Object.defineProperty(PointLight.prototype, "direction", {
  36501. get: function () {
  36502. return this._direction;
  36503. },
  36504. /**
  36505. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36506. */
  36507. set: function (value) {
  36508. var previousNeedCube = this.needCube();
  36509. this._direction = value;
  36510. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36511. this._shadowGenerator.recreateShadowMap();
  36512. }
  36513. },
  36514. enumerable: true,
  36515. configurable: true
  36516. });
  36517. /**
  36518. * Returns the string "PointLight"
  36519. */
  36520. PointLight.prototype.getClassName = function () {
  36521. return "PointLight";
  36522. };
  36523. /**
  36524. * Returns the integer 0.
  36525. */
  36526. PointLight.prototype.getTypeID = function () {
  36527. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36528. };
  36529. /**
  36530. * Specifies wether or not the shadowmap should be a cube texture.
  36531. */
  36532. PointLight.prototype.needCube = function () {
  36533. return !this.direction;
  36534. };
  36535. /**
  36536. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36537. */
  36538. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36539. if (this.direction) {
  36540. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36541. }
  36542. else {
  36543. switch (faceIndex) {
  36544. case 0:
  36545. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36546. case 1:
  36547. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36548. case 2:
  36549. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36550. case 3:
  36551. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36552. case 4:
  36553. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36554. case 5:
  36555. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36556. }
  36557. }
  36558. return BABYLON.Vector3.Zero();
  36559. };
  36560. /**
  36561. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36562. * - fov = PI / 2
  36563. * - aspect ratio : 1.0
  36564. * - z-near and far equal to the active camera minZ and maxZ.
  36565. * Returns the PointLight.
  36566. */
  36567. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36568. var activeCamera = this.getScene().activeCamera;
  36569. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36570. };
  36571. PointLight.prototype._buildUniformLayout = function () {
  36572. this._uniformBuffer.addUniform("vLightData", 4);
  36573. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36574. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36575. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36576. this._uniformBuffer.addUniform("depthValues", 2);
  36577. this._uniformBuffer.create();
  36578. };
  36579. /**
  36580. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36581. * Returns the PointLight.
  36582. */
  36583. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36584. if (this.computeTransformedInformation()) {
  36585. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36586. return this;
  36587. }
  36588. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36589. return this;
  36590. };
  36591. __decorate([
  36592. BABYLON.serialize()
  36593. ], PointLight.prototype, "shadowAngle", null);
  36594. return PointLight;
  36595. }(BABYLON.ShadowLight));
  36596. BABYLON.PointLight = PointLight;
  36597. })(BABYLON || (BABYLON = {}));
  36598. //# sourceMappingURL=babylon.pointLight.js.map
  36599. /// <reference path="babylon.light.ts" />
  36600. var BABYLON;
  36601. (function (BABYLON) {
  36602. var DirectionalLight = (function (_super) {
  36603. __extends(DirectionalLight, _super);
  36604. /**
  36605. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36606. * The directional light is emitted from everywhere in the given direction.
  36607. * It can cast shawdows.
  36608. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36609. */
  36610. function DirectionalLight(name, direction, scene) {
  36611. var _this = _super.call(this, name, scene) || this;
  36612. _this._shadowFrustumSize = 0;
  36613. _this._shadowOrthoScale = 0.5;
  36614. _this.autoUpdateExtends = true;
  36615. // Cache
  36616. _this._orthoLeft = Number.MAX_VALUE;
  36617. _this._orthoRight = Number.MIN_VALUE;
  36618. _this._orthoTop = Number.MIN_VALUE;
  36619. _this._orthoBottom = Number.MAX_VALUE;
  36620. _this.position = direction.scale(-1.0);
  36621. _this.direction = direction;
  36622. return _this;
  36623. }
  36624. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36625. /**
  36626. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36627. */
  36628. get: function () {
  36629. return this._shadowFrustumSize;
  36630. },
  36631. /**
  36632. * Specifies a fix frustum size for the shadow generation.
  36633. */
  36634. set: function (value) {
  36635. this._shadowFrustumSize = value;
  36636. this.forceProjectionMatrixCompute();
  36637. },
  36638. enumerable: true,
  36639. configurable: true
  36640. });
  36641. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36642. get: function () {
  36643. return this._shadowOrthoScale;
  36644. },
  36645. set: function (value) {
  36646. this._shadowOrthoScale = value;
  36647. this.forceProjectionMatrixCompute();
  36648. },
  36649. enumerable: true,
  36650. configurable: true
  36651. });
  36652. /**
  36653. * Returns the string "DirectionalLight".
  36654. */
  36655. DirectionalLight.prototype.getClassName = function () {
  36656. return "DirectionalLight";
  36657. };
  36658. /**
  36659. * Returns the integer 1.
  36660. */
  36661. DirectionalLight.prototype.getTypeID = function () {
  36662. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36663. };
  36664. /**
  36665. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36666. * Returns the DirectionalLight Shadow projection matrix.
  36667. */
  36668. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36669. if (this.shadowFrustumSize > 0) {
  36670. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36671. }
  36672. else {
  36673. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36674. }
  36675. };
  36676. /**
  36677. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36678. * Returns the DirectionalLight Shadow projection matrix.
  36679. */
  36680. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36681. var activeCamera = this.getScene().activeCamera;
  36682. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36683. };
  36684. /**
  36685. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36686. * Returns the DirectionalLight Shadow projection matrix.
  36687. */
  36688. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36689. var activeCamera = this.getScene().activeCamera;
  36690. // Check extends
  36691. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36692. var tempVector3 = BABYLON.Vector3.Zero();
  36693. this._orthoLeft = Number.MAX_VALUE;
  36694. this._orthoRight = Number.MIN_VALUE;
  36695. this._orthoTop = Number.MIN_VALUE;
  36696. this._orthoBottom = Number.MAX_VALUE;
  36697. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36698. var mesh = renderList[meshIndex];
  36699. if (!mesh) {
  36700. continue;
  36701. }
  36702. var boundingInfo = mesh.getBoundingInfo();
  36703. if (!boundingInfo) {
  36704. continue;
  36705. }
  36706. var boundingBox = boundingInfo.boundingBox;
  36707. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36708. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36709. if (tempVector3.x < this._orthoLeft)
  36710. this._orthoLeft = tempVector3.x;
  36711. if (tempVector3.y < this._orthoBottom)
  36712. this._orthoBottom = tempVector3.y;
  36713. if (tempVector3.x > this._orthoRight)
  36714. this._orthoRight = tempVector3.x;
  36715. if (tempVector3.y > this._orthoTop)
  36716. this._orthoTop = tempVector3.y;
  36717. }
  36718. }
  36719. }
  36720. var xOffset = this._orthoRight - this._orthoLeft;
  36721. var yOffset = this._orthoTop - this._orthoBottom;
  36722. 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);
  36723. };
  36724. DirectionalLight.prototype._buildUniformLayout = function () {
  36725. this._uniformBuffer.addUniform("vLightData", 4);
  36726. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36727. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36728. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36729. this._uniformBuffer.addUniform("depthValues", 2);
  36730. this._uniformBuffer.create();
  36731. };
  36732. /**
  36733. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36734. * Returns the DirectionalLight.
  36735. */
  36736. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36737. if (this.computeTransformedInformation()) {
  36738. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36739. return this;
  36740. }
  36741. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36742. return this;
  36743. };
  36744. /**
  36745. * Gets the minZ used for shadow according to both the scene and the light.
  36746. *
  36747. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36748. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36749. * @param activeCamera
  36750. */
  36751. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36752. return 1;
  36753. };
  36754. /**
  36755. * Gets the maxZ used for shadow according to both the scene and the light.
  36756. *
  36757. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36758. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36759. * @param activeCamera
  36760. */
  36761. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36762. return 1;
  36763. };
  36764. __decorate([
  36765. BABYLON.serialize()
  36766. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36767. __decorate([
  36768. BABYLON.serialize()
  36769. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36770. __decorate([
  36771. BABYLON.serialize()
  36772. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36773. return DirectionalLight;
  36774. }(BABYLON.ShadowLight));
  36775. BABYLON.DirectionalLight = DirectionalLight;
  36776. })(BABYLON || (BABYLON = {}));
  36777. //# sourceMappingURL=babylon.directionalLight.js.map
  36778. var BABYLON;
  36779. (function (BABYLON) {
  36780. var SpotLight = (function (_super) {
  36781. __extends(SpotLight, _super);
  36782. /**
  36783. * Creates a SpotLight object in the scene with the passed parameters :
  36784. * - `position` (Vector3) is the initial SpotLight position,
  36785. * - `direction` (Vector3) is the initial SpotLight direction,
  36786. * - `angle` (float, in radians) is the spot light cone angle,
  36787. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36788. * A spot light is a simply light oriented cone.
  36789. * It can cast shadows.
  36790. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36791. */
  36792. function SpotLight(name, position, direction, angle, exponent, scene) {
  36793. var _this = _super.call(this, name, scene) || this;
  36794. _this.position = position;
  36795. _this.direction = direction;
  36796. _this.angle = angle;
  36797. _this.exponent = exponent;
  36798. return _this;
  36799. }
  36800. Object.defineProperty(SpotLight.prototype, "angle", {
  36801. get: function () {
  36802. return this._angle;
  36803. },
  36804. set: function (value) {
  36805. this._angle = value;
  36806. this.forceProjectionMatrixCompute();
  36807. },
  36808. enumerable: true,
  36809. configurable: true
  36810. });
  36811. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36812. get: function () {
  36813. return this._shadowAngleScale;
  36814. },
  36815. /**
  36816. * Allows scaling the angle of the light for shadow generation only.
  36817. */
  36818. set: function (value) {
  36819. this._shadowAngleScale = value;
  36820. this.forceProjectionMatrixCompute();
  36821. },
  36822. enumerable: true,
  36823. configurable: true
  36824. });
  36825. /**
  36826. * Returns the string "SpotLight".
  36827. */
  36828. SpotLight.prototype.getClassName = function () {
  36829. return "SpotLight";
  36830. };
  36831. /**
  36832. * Returns the integer 2.
  36833. */
  36834. SpotLight.prototype.getTypeID = function () {
  36835. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36836. };
  36837. /**
  36838. * 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.
  36839. * Returns the SpotLight.
  36840. */
  36841. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36842. var activeCamera = this.getScene().activeCamera;
  36843. this._shadowAngleScale = this._shadowAngleScale || 1;
  36844. var angle = this._shadowAngleScale * this._angle;
  36845. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36846. };
  36847. SpotLight.prototype._buildUniformLayout = function () {
  36848. this._uniformBuffer.addUniform("vLightData", 4);
  36849. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36850. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36851. this._uniformBuffer.addUniform("vLightDirection", 3);
  36852. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36853. this._uniformBuffer.addUniform("depthValues", 2);
  36854. this._uniformBuffer.create();
  36855. };
  36856. /**
  36857. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36858. * Return the SpotLight.
  36859. */
  36860. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36861. var normalizeDirection;
  36862. if (this.computeTransformedInformation()) {
  36863. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36864. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36865. }
  36866. else {
  36867. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36868. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36869. }
  36870. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36871. return this;
  36872. };
  36873. __decorate([
  36874. BABYLON.serialize()
  36875. ], SpotLight.prototype, "angle", null);
  36876. __decorate([
  36877. BABYLON.serialize()
  36878. /**
  36879. * Allows scaling the angle of the light for shadow generation only.
  36880. */
  36881. ], SpotLight.prototype, "shadowAngleScale", null);
  36882. __decorate([
  36883. BABYLON.serialize()
  36884. ], SpotLight.prototype, "exponent", void 0);
  36885. return SpotLight;
  36886. }(BABYLON.ShadowLight));
  36887. BABYLON.SpotLight = SpotLight;
  36888. })(BABYLON || (BABYLON = {}));
  36889. //# sourceMappingURL=babylon.spotLight.js.map
  36890. var BABYLON;
  36891. (function (BABYLON) {
  36892. var AnimationRange = (function () {
  36893. function AnimationRange(name, from, to) {
  36894. this.name = name;
  36895. this.from = from;
  36896. this.to = to;
  36897. }
  36898. AnimationRange.prototype.clone = function () {
  36899. return new AnimationRange(this.name, this.from, this.to);
  36900. };
  36901. return AnimationRange;
  36902. }());
  36903. BABYLON.AnimationRange = AnimationRange;
  36904. /**
  36905. * Composed of a frame, and an action function
  36906. */
  36907. var AnimationEvent = (function () {
  36908. function AnimationEvent(frame, action, onlyOnce) {
  36909. this.frame = frame;
  36910. this.action = action;
  36911. this.onlyOnce = onlyOnce;
  36912. this.isDone = false;
  36913. }
  36914. return AnimationEvent;
  36915. }());
  36916. BABYLON.AnimationEvent = AnimationEvent;
  36917. var PathCursor = (function () {
  36918. function PathCursor(path) {
  36919. this.path = path;
  36920. this._onchange = new Array();
  36921. this.value = 0;
  36922. this.animations = new Array();
  36923. }
  36924. PathCursor.prototype.getPoint = function () {
  36925. var point = this.path.getPointAtLengthPosition(this.value);
  36926. return new BABYLON.Vector3(point.x, 0, point.y);
  36927. };
  36928. PathCursor.prototype.moveAhead = function (step) {
  36929. if (step === void 0) { step = 0.002; }
  36930. this.move(step);
  36931. return this;
  36932. };
  36933. PathCursor.prototype.moveBack = function (step) {
  36934. if (step === void 0) { step = 0.002; }
  36935. this.move(-step);
  36936. return this;
  36937. };
  36938. PathCursor.prototype.move = function (step) {
  36939. if (Math.abs(step) > 1) {
  36940. throw "step size should be less than 1.";
  36941. }
  36942. this.value += step;
  36943. this.ensureLimits();
  36944. this.raiseOnChange();
  36945. return this;
  36946. };
  36947. PathCursor.prototype.ensureLimits = function () {
  36948. while (this.value > 1) {
  36949. this.value -= 1;
  36950. }
  36951. while (this.value < 0) {
  36952. this.value += 1;
  36953. }
  36954. return this;
  36955. };
  36956. // used by animation engine
  36957. PathCursor.prototype.markAsDirty = function (propertyName) {
  36958. this.ensureLimits();
  36959. this.raiseOnChange();
  36960. return this;
  36961. };
  36962. PathCursor.prototype.raiseOnChange = function () {
  36963. var _this = this;
  36964. this._onchange.forEach(function (f) { return f(_this); });
  36965. return this;
  36966. };
  36967. PathCursor.prototype.onchange = function (f) {
  36968. this._onchange.push(f);
  36969. return this;
  36970. };
  36971. return PathCursor;
  36972. }());
  36973. BABYLON.PathCursor = PathCursor;
  36974. var Animation = (function () {
  36975. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  36976. this.name = name;
  36977. this.targetProperty = targetProperty;
  36978. this.framePerSecond = framePerSecond;
  36979. this.dataType = dataType;
  36980. this.loopMode = loopMode;
  36981. this.enableBlending = enableBlending;
  36982. this._runtimeAnimations = new Array();
  36983. // The set of event that will be linked to this animation
  36984. this._events = new Array();
  36985. this.blendingSpeed = 0.01;
  36986. this._ranges = {};
  36987. this.targetPropertyPath = targetProperty.split(".");
  36988. this.dataType = dataType;
  36989. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  36990. }
  36991. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  36992. var dataType = undefined;
  36993. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  36994. dataType = Animation.ANIMATIONTYPE_FLOAT;
  36995. }
  36996. else if (from instanceof BABYLON.Quaternion) {
  36997. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  36998. }
  36999. else if (from instanceof BABYLON.Vector3) {
  37000. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  37001. }
  37002. else if (from instanceof BABYLON.Vector2) {
  37003. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  37004. }
  37005. else if (from instanceof BABYLON.Color3) {
  37006. dataType = Animation.ANIMATIONTYPE_COLOR3;
  37007. }
  37008. else if (from instanceof BABYLON.Size) {
  37009. dataType = Animation.ANIMATIONTYPE_SIZE;
  37010. }
  37011. if (dataType == undefined) {
  37012. return null;
  37013. }
  37014. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  37015. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  37016. animation.setKeys(keys);
  37017. if (easingFunction !== undefined) {
  37018. animation.setEasingFunction(easingFunction);
  37019. }
  37020. return animation;
  37021. };
  37022. /**
  37023. * Sets up an animation.
  37024. * @param property the property to animate
  37025. * @param animationType the animation type to apply
  37026. * @param easingFunction the easing function used in the animation
  37027. * @returns The created animation
  37028. */
  37029. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  37030. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37031. animation.setEasingFunction(easingFunction);
  37032. return animation;
  37033. };
  37034. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  37035. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  37036. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  37037. };
  37038. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  37039. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  37040. node.animations.push(animation);
  37041. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  37042. };
  37043. /**
  37044. * Transition property of the Camera to the target Value.
  37045. * @param property The property to transition
  37046. * @param targetValue The target Value of the property
  37047. * @param host The object where the property to animate belongs
  37048. * @param scene Scene used to run the animation
  37049. * @param frameRate Framerate (in frame/s) to use
  37050. * @param transition The transition type we want to use
  37051. * @param duration The duration of the animation, in milliseconds
  37052. * @param onAnimationEnd Call back trigger at the end of the animation.
  37053. */
  37054. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  37055. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  37056. if (duration <= 0) {
  37057. host[property] = targetValue;
  37058. if (onAnimationEnd) {
  37059. onAnimationEnd();
  37060. }
  37061. return;
  37062. }
  37063. var endFrame = frameRate * (duration / 1000);
  37064. transition.setKeys([{
  37065. frame: 0,
  37066. value: host[property].clone ? host[property].clone() : host[property]
  37067. },
  37068. {
  37069. frame: endFrame,
  37070. value: targetValue
  37071. }]);
  37072. if (!host.animations) {
  37073. host.animations = [];
  37074. }
  37075. host.animations.push(transition);
  37076. var animation = scene.beginAnimation(host, 0, endFrame, false);
  37077. animation.onAnimationEnd = onAnimationEnd;
  37078. return animation;
  37079. };
  37080. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  37081. /**
  37082. * Return the array of runtime animations currently using this animation
  37083. */
  37084. get: function () {
  37085. return this._runtimeAnimations;
  37086. },
  37087. enumerable: true,
  37088. configurable: true
  37089. });
  37090. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  37091. get: function () {
  37092. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  37093. var runtimeAnimation = _a[_i];
  37094. if (!runtimeAnimation.isStopped) {
  37095. return true;
  37096. }
  37097. }
  37098. return false;
  37099. },
  37100. enumerable: true,
  37101. configurable: true
  37102. });
  37103. // Methods
  37104. /**
  37105. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  37106. */
  37107. Animation.prototype.toString = function (fullDetails) {
  37108. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  37109. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  37110. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  37111. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  37112. if (fullDetails) {
  37113. ret += ", Ranges: {";
  37114. var first = true;
  37115. for (var name in this._ranges) {
  37116. if (first) {
  37117. ret += ", ";
  37118. first = false;
  37119. }
  37120. ret += name;
  37121. }
  37122. ret += "}";
  37123. }
  37124. return ret;
  37125. };
  37126. /**
  37127. * Add an event to this animation.
  37128. */
  37129. Animation.prototype.addEvent = function (event) {
  37130. this._events.push(event);
  37131. };
  37132. /**
  37133. * Remove all events found at the given frame
  37134. * @param frame
  37135. */
  37136. Animation.prototype.removeEvents = function (frame) {
  37137. for (var index = 0; index < this._events.length; index++) {
  37138. if (this._events[index].frame === frame) {
  37139. this._events.splice(index, 1);
  37140. index--;
  37141. }
  37142. }
  37143. };
  37144. Animation.prototype.getEvents = function () {
  37145. return this._events;
  37146. };
  37147. Animation.prototype.createRange = function (name, from, to) {
  37148. // check name not already in use; could happen for bones after serialized
  37149. if (!this._ranges[name]) {
  37150. this._ranges[name] = new AnimationRange(name, from, to);
  37151. }
  37152. };
  37153. Animation.prototype.deleteRange = function (name, deleteFrames) {
  37154. if (deleteFrames === void 0) { deleteFrames = true; }
  37155. if (this._ranges[name]) {
  37156. if (deleteFrames) {
  37157. var from = this._ranges[name].from;
  37158. var to = this._ranges[name].to;
  37159. // this loop MUST go high to low for multiple splices to work
  37160. for (var key = this._keys.length - 1; key >= 0; key--) {
  37161. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  37162. this._keys.splice(key, 1);
  37163. }
  37164. }
  37165. }
  37166. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  37167. }
  37168. };
  37169. Animation.prototype.getRange = function (name) {
  37170. return this._ranges[name];
  37171. };
  37172. Animation.prototype.getKeys = function () {
  37173. return this._keys;
  37174. };
  37175. Animation.prototype.getHighestFrame = function () {
  37176. var ret = 0;
  37177. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  37178. if (ret < this._keys[key].frame) {
  37179. ret = this._keys[key].frame;
  37180. }
  37181. }
  37182. return ret;
  37183. };
  37184. Animation.prototype.getEasingFunction = function () {
  37185. return this._easingFunction;
  37186. };
  37187. Animation.prototype.setEasingFunction = function (easingFunction) {
  37188. this._easingFunction = easingFunction;
  37189. };
  37190. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  37191. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  37192. };
  37193. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37194. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37195. };
  37196. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  37197. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  37198. };
  37199. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37200. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  37201. };
  37202. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  37203. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  37204. };
  37205. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37206. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37207. };
  37208. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  37209. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  37210. };
  37211. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37212. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37213. };
  37214. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  37215. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  37216. };
  37217. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  37218. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  37219. };
  37220. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  37221. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  37222. };
  37223. Animation.prototype.clone = function () {
  37224. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  37225. clone.enableBlending = this.enableBlending;
  37226. clone.blendingSpeed = this.blendingSpeed;
  37227. if (this._keys) {
  37228. clone.setKeys(this._keys);
  37229. }
  37230. if (this._ranges) {
  37231. clone._ranges = {};
  37232. for (var name in this._ranges) {
  37233. clone._ranges[name] = this._ranges[name].clone();
  37234. }
  37235. }
  37236. return clone;
  37237. };
  37238. Animation.prototype.setKeys = function (values) {
  37239. this._keys = values.slice(0);
  37240. };
  37241. Animation.prototype.serialize = function () {
  37242. var serializationObject = {};
  37243. serializationObject.name = this.name;
  37244. serializationObject.property = this.targetProperty;
  37245. serializationObject.framePerSecond = this.framePerSecond;
  37246. serializationObject.dataType = this.dataType;
  37247. serializationObject.loopBehavior = this.loopMode;
  37248. serializationObject.enableBlending = this.enableBlending;
  37249. serializationObject.blendingSpeed = this.blendingSpeed;
  37250. var dataType = this.dataType;
  37251. serializationObject.keys = [];
  37252. var keys = this.getKeys();
  37253. for (var index = 0; index < keys.length; index++) {
  37254. var animationKey = keys[index];
  37255. var key = {};
  37256. key.frame = animationKey.frame;
  37257. switch (dataType) {
  37258. case Animation.ANIMATIONTYPE_FLOAT:
  37259. key.values = [animationKey.value];
  37260. break;
  37261. case Animation.ANIMATIONTYPE_QUATERNION:
  37262. case Animation.ANIMATIONTYPE_MATRIX:
  37263. case Animation.ANIMATIONTYPE_VECTOR3:
  37264. case Animation.ANIMATIONTYPE_COLOR3:
  37265. key.values = animationKey.value.asArray();
  37266. break;
  37267. }
  37268. serializationObject.keys.push(key);
  37269. }
  37270. serializationObject.ranges = [];
  37271. for (var name in this._ranges) {
  37272. var range = {};
  37273. range.name = name;
  37274. range.from = this._ranges[name].from;
  37275. range.to = this._ranges[name].to;
  37276. serializationObject.ranges.push(range);
  37277. }
  37278. return serializationObject;
  37279. };
  37280. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  37281. get: function () {
  37282. return Animation._ANIMATIONTYPE_FLOAT;
  37283. },
  37284. enumerable: true,
  37285. configurable: true
  37286. });
  37287. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  37288. get: function () {
  37289. return Animation._ANIMATIONTYPE_VECTOR3;
  37290. },
  37291. enumerable: true,
  37292. configurable: true
  37293. });
  37294. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  37295. get: function () {
  37296. return Animation._ANIMATIONTYPE_VECTOR2;
  37297. },
  37298. enumerable: true,
  37299. configurable: true
  37300. });
  37301. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  37302. get: function () {
  37303. return Animation._ANIMATIONTYPE_SIZE;
  37304. },
  37305. enumerable: true,
  37306. configurable: true
  37307. });
  37308. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  37309. get: function () {
  37310. return Animation._ANIMATIONTYPE_QUATERNION;
  37311. },
  37312. enumerable: true,
  37313. configurable: true
  37314. });
  37315. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  37316. get: function () {
  37317. return Animation._ANIMATIONTYPE_MATRIX;
  37318. },
  37319. enumerable: true,
  37320. configurable: true
  37321. });
  37322. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  37323. get: function () {
  37324. return Animation._ANIMATIONTYPE_COLOR3;
  37325. },
  37326. enumerable: true,
  37327. configurable: true
  37328. });
  37329. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  37330. get: function () {
  37331. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  37332. },
  37333. enumerable: true,
  37334. configurable: true
  37335. });
  37336. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  37337. get: function () {
  37338. return Animation._ANIMATIONLOOPMODE_CYCLE;
  37339. },
  37340. enumerable: true,
  37341. configurable: true
  37342. });
  37343. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  37344. get: function () {
  37345. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  37346. },
  37347. enumerable: true,
  37348. configurable: true
  37349. });
  37350. Animation.Parse = function (parsedAnimation) {
  37351. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  37352. var dataType = parsedAnimation.dataType;
  37353. var keys = [];
  37354. var data;
  37355. var index;
  37356. if (parsedAnimation.enableBlending) {
  37357. animation.enableBlending = parsedAnimation.enableBlending;
  37358. }
  37359. if (parsedAnimation.blendingSpeed) {
  37360. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  37361. }
  37362. for (index = 0; index < parsedAnimation.keys.length; index++) {
  37363. var key = parsedAnimation.keys[index];
  37364. switch (dataType) {
  37365. case Animation.ANIMATIONTYPE_FLOAT:
  37366. data = key.values[0];
  37367. break;
  37368. case Animation.ANIMATIONTYPE_QUATERNION:
  37369. data = BABYLON.Quaternion.FromArray(key.values);
  37370. break;
  37371. case Animation.ANIMATIONTYPE_MATRIX:
  37372. data = BABYLON.Matrix.FromArray(key.values);
  37373. break;
  37374. case Animation.ANIMATIONTYPE_COLOR3:
  37375. data = BABYLON.Color3.FromArray(key.values);
  37376. break;
  37377. case Animation.ANIMATIONTYPE_VECTOR3:
  37378. default:
  37379. data = BABYLON.Vector3.FromArray(key.values);
  37380. break;
  37381. }
  37382. keys.push({
  37383. frame: key.frame,
  37384. value: data
  37385. });
  37386. }
  37387. animation.setKeys(keys);
  37388. if (parsedAnimation.ranges) {
  37389. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  37390. data = parsedAnimation.ranges[index];
  37391. animation.createRange(data.name, data.from, data.to);
  37392. }
  37393. }
  37394. return animation;
  37395. };
  37396. Animation.AppendSerializedAnimations = function (source, destination) {
  37397. if (source.animations) {
  37398. destination.animations = [];
  37399. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  37400. var animation = source.animations[animationIndex];
  37401. destination.animations.push(animation.serialize());
  37402. }
  37403. }
  37404. };
  37405. Animation.AllowMatricesInterpolation = false;
  37406. // Statics
  37407. Animation._ANIMATIONTYPE_FLOAT = 0;
  37408. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  37409. Animation._ANIMATIONTYPE_QUATERNION = 2;
  37410. Animation._ANIMATIONTYPE_MATRIX = 3;
  37411. Animation._ANIMATIONTYPE_COLOR3 = 4;
  37412. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  37413. Animation._ANIMATIONTYPE_SIZE = 6;
  37414. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  37415. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  37416. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  37417. return Animation;
  37418. }());
  37419. BABYLON.Animation = Animation;
  37420. })(BABYLON || (BABYLON = {}));
  37421. //# sourceMappingURL=babylon.animation.js.map
  37422. var BABYLON;
  37423. (function (BABYLON) {
  37424. var RuntimeAnimation = (function () {
  37425. function RuntimeAnimation(target, animation) {
  37426. this._offsetsCache = {};
  37427. this._highLimitsCache = {};
  37428. this._stopped = false;
  37429. this._blendingFactor = 0;
  37430. this._animation = animation;
  37431. this._target = target;
  37432. animation._runtimeAnimations.push(this);
  37433. }
  37434. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  37435. get: function () {
  37436. return this._animation;
  37437. },
  37438. enumerable: true,
  37439. configurable: true
  37440. });
  37441. RuntimeAnimation.prototype.reset = function () {
  37442. this._offsetsCache = {};
  37443. this._highLimitsCache = {};
  37444. this.currentFrame = 0;
  37445. this._blendingFactor = 0;
  37446. this._originalBlendValue = null;
  37447. };
  37448. RuntimeAnimation.prototype.isStopped = function () {
  37449. return this._stopped;
  37450. };
  37451. RuntimeAnimation.prototype.dispose = function () {
  37452. var index = this._animation.runtimeAnimations.indexOf(this);
  37453. if (index > -1) {
  37454. this._animation.runtimeAnimations.splice(index, 1);
  37455. }
  37456. };
  37457. RuntimeAnimation.prototype._getKeyValue = function (value) {
  37458. if (typeof value === "function") {
  37459. return value();
  37460. }
  37461. return value;
  37462. };
  37463. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  37464. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  37465. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  37466. }
  37467. this.currentFrame = currentFrame;
  37468. var keys = this._animation.getKeys();
  37469. // Try to get a hash to find the right key
  37470. 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));
  37471. if (keys[startKeyIndex].frame >= currentFrame) {
  37472. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  37473. startKeyIndex--;
  37474. }
  37475. }
  37476. for (var key = startKeyIndex; key < keys.length; key++) {
  37477. var endKey = keys[key + 1];
  37478. if (endKey.frame >= currentFrame) {
  37479. var startKey = keys[key];
  37480. var startValue = this._getKeyValue(startKey.value);
  37481. var endValue = this._getKeyValue(endKey.value);
  37482. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  37483. var frameDelta = endKey.frame - startKey.frame;
  37484. // gradient : percent of currentFrame between the frame inf and the frame sup
  37485. var gradient = (currentFrame - startKey.frame) / frameDelta;
  37486. // check for easingFunction and correction of gradient
  37487. var easingFunction = this._animation.getEasingFunction();
  37488. if (easingFunction != null) {
  37489. gradient = easingFunction.ease(gradient);
  37490. }
  37491. switch (this._animation.dataType) {
  37492. // Float
  37493. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37494. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  37495. switch (loopMode) {
  37496. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37497. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37498. return floatValue;
  37499. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37500. return offsetValue * repeatCount + floatValue;
  37501. }
  37502. break;
  37503. // Quaternion
  37504. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37505. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  37506. switch (loopMode) {
  37507. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37508. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37509. return quatValue;
  37510. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37511. return quatValue.add(offsetValue.scale(repeatCount));
  37512. }
  37513. return quatValue;
  37514. // Vector3
  37515. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37516. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  37517. switch (loopMode) {
  37518. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37519. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37520. return vec3Value;
  37521. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37522. return vec3Value.add(offsetValue.scale(repeatCount));
  37523. }
  37524. // Vector2
  37525. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37526. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  37527. switch (loopMode) {
  37528. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37529. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37530. return vec2Value;
  37531. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37532. return vec2Value.add(offsetValue.scale(repeatCount));
  37533. }
  37534. // Size
  37535. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37536. switch (loopMode) {
  37537. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37538. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37539. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  37540. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37541. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37542. }
  37543. // Color3
  37544. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37545. switch (loopMode) {
  37546. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37547. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37548. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  37549. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37550. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37551. }
  37552. // Matrix
  37553. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  37554. switch (loopMode) {
  37555. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37556. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37557. if (BABYLON.Animation.AllowMatricesInterpolation) {
  37558. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  37559. }
  37560. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37561. return startValue;
  37562. }
  37563. default:
  37564. break;
  37565. }
  37566. break;
  37567. }
  37568. }
  37569. return this._getKeyValue(keys[keys.length - 1].value);
  37570. };
  37571. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  37572. if (blend === void 0) { blend = false; }
  37573. // Set value
  37574. var path;
  37575. var destination;
  37576. var targetPropertyPath = this._animation.targetPropertyPath;
  37577. if (targetPropertyPath.length > 1) {
  37578. var property = this._target[targetPropertyPath[0]];
  37579. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  37580. property = property[targetPropertyPath[index]];
  37581. }
  37582. path = targetPropertyPath[targetPropertyPath.length - 1];
  37583. destination = property;
  37584. }
  37585. else {
  37586. path = targetPropertyPath[0];
  37587. destination = this._target;
  37588. }
  37589. // Blending
  37590. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  37591. if (!this._originalBlendValue) {
  37592. if (destination[path].clone) {
  37593. this._originalBlendValue = destination[path].clone();
  37594. }
  37595. else {
  37596. this._originalBlendValue = destination[path];
  37597. }
  37598. }
  37599. if (this._originalBlendValue.prototype) {
  37600. if (this._originalBlendValue.prototype.Lerp) {
  37601. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  37602. }
  37603. else {
  37604. destination[path] = currentValue;
  37605. }
  37606. }
  37607. else if (this._originalBlendValue.m) {
  37608. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  37609. }
  37610. else {
  37611. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  37612. }
  37613. this._blendingFactor += this._animation.blendingSpeed;
  37614. }
  37615. else {
  37616. destination[path] = currentValue;
  37617. }
  37618. if (this._target.markAsDirty) {
  37619. this._target.markAsDirty(this._animation.targetProperty);
  37620. }
  37621. };
  37622. RuntimeAnimation.prototype.goToFrame = function (frame) {
  37623. var keys = this._animation.getKeys();
  37624. if (frame < keys[0].frame) {
  37625. frame = keys[0].frame;
  37626. }
  37627. else if (frame > keys[keys.length - 1].frame) {
  37628. frame = keys[keys.length - 1].frame;
  37629. }
  37630. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  37631. this.setValue(currentValue);
  37632. };
  37633. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  37634. if (blend === void 0) { blend = false; }
  37635. var targetPropertyPath = this._animation.targetPropertyPath;
  37636. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  37637. this._stopped = true;
  37638. return false;
  37639. }
  37640. var returnValue = true;
  37641. var keys = this._animation.getKeys();
  37642. // Adding a start key at frame 0 if missing
  37643. if (keys[0].frame !== 0) {
  37644. var newKey = { frame: 0, value: keys[0].value };
  37645. keys.splice(0, 0, newKey);
  37646. }
  37647. // Check limits
  37648. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  37649. from = keys[0].frame;
  37650. }
  37651. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  37652. to = keys[keys.length - 1].frame;
  37653. }
  37654. //to and from cannot be the same key
  37655. if (from === to) {
  37656. from++;
  37657. }
  37658. // Compute ratio
  37659. var range = to - from;
  37660. var offsetValue;
  37661. // ratio represents the frame delta between from and to
  37662. var ratio = delay * (this._animation.framePerSecond * speedRatio) / 1000.0;
  37663. var highLimitValue = 0;
  37664. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  37665. returnValue = false;
  37666. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  37667. }
  37668. else {
  37669. // Get max value if required
  37670. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  37671. var keyOffset = to.toString() + from.toString();
  37672. if (!this._offsetsCache[keyOffset]) {
  37673. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  37674. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  37675. switch (this._animation.dataType) {
  37676. // Float
  37677. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37678. this._offsetsCache[keyOffset] = toValue - fromValue;
  37679. break;
  37680. // Quaternion
  37681. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37682. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37683. break;
  37684. // Vector3
  37685. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37686. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37687. // Vector2
  37688. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37689. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37690. // Size
  37691. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37692. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37693. // Color3
  37694. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37695. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37696. default:
  37697. break;
  37698. }
  37699. this._highLimitsCache[keyOffset] = toValue;
  37700. }
  37701. highLimitValue = this._highLimitsCache[keyOffset];
  37702. offsetValue = this._offsetsCache[keyOffset];
  37703. }
  37704. }
  37705. if (offsetValue === undefined) {
  37706. switch (this._animation.dataType) {
  37707. // Float
  37708. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37709. offsetValue = 0;
  37710. break;
  37711. // Quaternion
  37712. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37713. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  37714. break;
  37715. // Vector3
  37716. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37717. offsetValue = BABYLON.Vector3.Zero();
  37718. break;
  37719. // Vector2
  37720. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37721. offsetValue = BABYLON.Vector2.Zero();
  37722. break;
  37723. // Size
  37724. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37725. offsetValue = BABYLON.Size.Zero();
  37726. break;
  37727. // Color3
  37728. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37729. offsetValue = BABYLON.Color3.Black();
  37730. }
  37731. }
  37732. // Compute value
  37733. var repeatCount = (ratio / range) >> 0;
  37734. var currentFrame = returnValue ? from + ratio % range : to;
  37735. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  37736. // Set value
  37737. this.setValue(currentValue);
  37738. // Check events
  37739. var events = this._animation.getEvents();
  37740. for (var index = 0; index < events.length; index++) {
  37741. // Make sure current frame has passed event frame and that event frame is within the current range
  37742. // Also, handle both forward and reverse animations
  37743. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  37744. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  37745. var event = events[index];
  37746. if (!event.isDone) {
  37747. // If event should be done only once, remove it.
  37748. if (event.onlyOnce) {
  37749. events.splice(index, 1);
  37750. index--;
  37751. }
  37752. event.isDone = true;
  37753. event.action();
  37754. } // Don't do anything if the event has already be done.
  37755. }
  37756. else if (events[index].isDone && !events[index].onlyOnce) {
  37757. // reset event, the animation is looping
  37758. events[index].isDone = false;
  37759. }
  37760. }
  37761. if (!returnValue) {
  37762. this._stopped = true;
  37763. }
  37764. return returnValue;
  37765. };
  37766. return RuntimeAnimation;
  37767. }());
  37768. BABYLON.RuntimeAnimation = RuntimeAnimation;
  37769. })(BABYLON || (BABYLON = {}));
  37770. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  37771. var BABYLON;
  37772. (function (BABYLON) {
  37773. var Animatable = (function () {
  37774. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  37775. if (fromFrame === void 0) { fromFrame = 0; }
  37776. if (toFrame === void 0) { toFrame = 100; }
  37777. if (loopAnimation === void 0) { loopAnimation = false; }
  37778. if (speedRatio === void 0) { speedRatio = 1.0; }
  37779. this.target = target;
  37780. this.fromFrame = fromFrame;
  37781. this.toFrame = toFrame;
  37782. this.loopAnimation = loopAnimation;
  37783. this.speedRatio = speedRatio;
  37784. this.onAnimationEnd = onAnimationEnd;
  37785. this._localDelayOffset = null;
  37786. this._pausedDelay = null;
  37787. this._runtimeAnimations = new Array();
  37788. this._paused = false;
  37789. this.animationStarted = false;
  37790. if (animations) {
  37791. this.appendAnimations(target, animations);
  37792. }
  37793. this._scene = scene;
  37794. scene._activeAnimatables.push(this);
  37795. }
  37796. // Methods
  37797. Animatable.prototype.getAnimations = function () {
  37798. return this._runtimeAnimations;
  37799. };
  37800. Animatable.prototype.appendAnimations = function (target, animations) {
  37801. for (var index = 0; index < animations.length; index++) {
  37802. var animation = animations[index];
  37803. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  37804. }
  37805. };
  37806. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  37807. var runtimeAnimations = this._runtimeAnimations;
  37808. for (var index = 0; index < runtimeAnimations.length; index++) {
  37809. if (runtimeAnimations[index].animation.targetProperty === property) {
  37810. return runtimeAnimations[index].animation;
  37811. }
  37812. }
  37813. return null;
  37814. };
  37815. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  37816. var runtimeAnimations = this._runtimeAnimations;
  37817. for (var index = 0; index < runtimeAnimations.length; index++) {
  37818. if (runtimeAnimations[index].animation.targetProperty === property) {
  37819. return runtimeAnimations[index];
  37820. }
  37821. }
  37822. return null;
  37823. };
  37824. Animatable.prototype.reset = function () {
  37825. var runtimeAnimations = this._runtimeAnimations;
  37826. for (var index = 0; index < runtimeAnimations.length; index++) {
  37827. runtimeAnimations[index].reset();
  37828. }
  37829. this._localDelayOffset = null;
  37830. this._pausedDelay = null;
  37831. };
  37832. Animatable.prototype.enableBlending = function (blendingSpeed) {
  37833. var runtimeAnimations = this._runtimeAnimations;
  37834. for (var index = 0; index < runtimeAnimations.length; index++) {
  37835. runtimeAnimations[index].animation.enableBlending = true;
  37836. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  37837. }
  37838. };
  37839. Animatable.prototype.disableBlending = function () {
  37840. var runtimeAnimations = this._runtimeAnimations;
  37841. for (var index = 0; index < runtimeAnimations.length; index++) {
  37842. runtimeAnimations[index].animation.enableBlending = false;
  37843. }
  37844. };
  37845. Animatable.prototype.goToFrame = function (frame) {
  37846. var runtimeAnimations = this._runtimeAnimations;
  37847. if (runtimeAnimations[0]) {
  37848. var fps = runtimeAnimations[0].animation.framePerSecond;
  37849. var currentFrame = runtimeAnimations[0].currentFrame;
  37850. var adjustTime = frame - currentFrame;
  37851. var delay = adjustTime * 1000 / fps;
  37852. this._localDelayOffset -= delay;
  37853. }
  37854. for (var index = 0; index < runtimeAnimations.length; index++) {
  37855. runtimeAnimations[index].goToFrame(frame);
  37856. }
  37857. };
  37858. Animatable.prototype.pause = function () {
  37859. if (this._paused) {
  37860. return;
  37861. }
  37862. this._paused = true;
  37863. };
  37864. Animatable.prototype.restart = function () {
  37865. this._paused = false;
  37866. };
  37867. Animatable.prototype.stop = function (animationName) {
  37868. if (animationName) {
  37869. var idx = this._scene._activeAnimatables.indexOf(this);
  37870. if (idx > -1) {
  37871. var runtimeAnimations = this._runtimeAnimations;
  37872. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  37873. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  37874. continue;
  37875. }
  37876. runtimeAnimations[index].dispose();
  37877. runtimeAnimations.splice(index, 1);
  37878. }
  37879. if (runtimeAnimations.length == 0) {
  37880. this._scene._activeAnimatables.splice(idx, 1);
  37881. if (this.onAnimationEnd) {
  37882. this.onAnimationEnd();
  37883. }
  37884. }
  37885. }
  37886. }
  37887. else {
  37888. var index = this._scene._activeAnimatables.indexOf(this);
  37889. if (index > -1) {
  37890. this._scene._activeAnimatables.splice(index, 1);
  37891. var runtimeAnimations = this._runtimeAnimations;
  37892. for (var index = 0; index < runtimeAnimations.length; index++) {
  37893. runtimeAnimations[index].dispose();
  37894. }
  37895. if (this.onAnimationEnd) {
  37896. this.onAnimationEnd();
  37897. }
  37898. }
  37899. }
  37900. };
  37901. Animatable.prototype._animate = function (delay) {
  37902. if (this._paused) {
  37903. this.animationStarted = false;
  37904. if (this._pausedDelay === null) {
  37905. this._pausedDelay = delay;
  37906. }
  37907. return true;
  37908. }
  37909. if (this._localDelayOffset === null) {
  37910. this._localDelayOffset = delay;
  37911. }
  37912. else if (this._pausedDelay !== null) {
  37913. this._localDelayOffset += delay - this._pausedDelay;
  37914. this._pausedDelay = null;
  37915. }
  37916. // Animating
  37917. var running = false;
  37918. var runtimeAnimations = this._runtimeAnimations;
  37919. var index;
  37920. for (index = 0; index < runtimeAnimations.length; index++) {
  37921. var animation = runtimeAnimations[index];
  37922. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  37923. running = running || isRunning;
  37924. }
  37925. this.animationStarted = running;
  37926. if (!running) {
  37927. // Remove from active animatables
  37928. index = this._scene._activeAnimatables.indexOf(this);
  37929. this._scene._activeAnimatables.splice(index, 1);
  37930. // Dispose all runtime animations
  37931. for (index = 0; index < runtimeAnimations.length; index++) {
  37932. runtimeAnimations[index].dispose();
  37933. }
  37934. }
  37935. if (!running && this.onAnimationEnd) {
  37936. this.onAnimationEnd();
  37937. this.onAnimationEnd = null;
  37938. }
  37939. return running;
  37940. };
  37941. return Animatable;
  37942. }());
  37943. BABYLON.Animatable = Animatable;
  37944. })(BABYLON || (BABYLON = {}));
  37945. //# sourceMappingURL=babylon.animatable.js.map
  37946. var BABYLON;
  37947. (function (BABYLON) {
  37948. var EasingFunction = (function () {
  37949. function EasingFunction() {
  37950. // Properties
  37951. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  37952. }
  37953. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  37954. get: function () {
  37955. return EasingFunction._EASINGMODE_EASEIN;
  37956. },
  37957. enumerable: true,
  37958. configurable: true
  37959. });
  37960. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  37961. get: function () {
  37962. return EasingFunction._EASINGMODE_EASEOUT;
  37963. },
  37964. enumerable: true,
  37965. configurable: true
  37966. });
  37967. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  37968. get: function () {
  37969. return EasingFunction._EASINGMODE_EASEINOUT;
  37970. },
  37971. enumerable: true,
  37972. configurable: true
  37973. });
  37974. EasingFunction.prototype.setEasingMode = function (easingMode) {
  37975. var n = Math.min(Math.max(easingMode, 0), 2);
  37976. this._easingMode = n;
  37977. };
  37978. EasingFunction.prototype.getEasingMode = function () {
  37979. return this._easingMode;
  37980. };
  37981. EasingFunction.prototype.easeInCore = function (gradient) {
  37982. throw new Error('You must implement this method');
  37983. };
  37984. EasingFunction.prototype.ease = function (gradient) {
  37985. switch (this._easingMode) {
  37986. case EasingFunction.EASINGMODE_EASEIN:
  37987. return this.easeInCore(gradient);
  37988. case EasingFunction.EASINGMODE_EASEOUT:
  37989. return (1 - this.easeInCore(1 - gradient));
  37990. }
  37991. if (gradient >= 0.5) {
  37992. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  37993. }
  37994. return (this.easeInCore(gradient * 2) * 0.5);
  37995. };
  37996. //Statics
  37997. EasingFunction._EASINGMODE_EASEIN = 0;
  37998. EasingFunction._EASINGMODE_EASEOUT = 1;
  37999. EasingFunction._EASINGMODE_EASEINOUT = 2;
  38000. return EasingFunction;
  38001. }());
  38002. BABYLON.EasingFunction = EasingFunction;
  38003. var CircleEase = (function (_super) {
  38004. __extends(CircleEase, _super);
  38005. function CircleEase() {
  38006. return _super !== null && _super.apply(this, arguments) || this;
  38007. }
  38008. CircleEase.prototype.easeInCore = function (gradient) {
  38009. gradient = Math.max(0, Math.min(1, gradient));
  38010. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  38011. };
  38012. return CircleEase;
  38013. }(EasingFunction));
  38014. BABYLON.CircleEase = CircleEase;
  38015. var BackEase = (function (_super) {
  38016. __extends(BackEase, _super);
  38017. function BackEase(amplitude) {
  38018. if (amplitude === void 0) { amplitude = 1; }
  38019. var _this = _super.call(this) || this;
  38020. _this.amplitude = amplitude;
  38021. return _this;
  38022. }
  38023. BackEase.prototype.easeInCore = function (gradient) {
  38024. var num = Math.max(0, this.amplitude);
  38025. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  38026. };
  38027. return BackEase;
  38028. }(EasingFunction));
  38029. BABYLON.BackEase = BackEase;
  38030. var BounceEase = (function (_super) {
  38031. __extends(BounceEase, _super);
  38032. function BounceEase(bounces, bounciness) {
  38033. if (bounces === void 0) { bounces = 3; }
  38034. if (bounciness === void 0) { bounciness = 2; }
  38035. var _this = _super.call(this) || this;
  38036. _this.bounces = bounces;
  38037. _this.bounciness = bounciness;
  38038. return _this;
  38039. }
  38040. BounceEase.prototype.easeInCore = function (gradient) {
  38041. var y = Math.max(0.0, this.bounces);
  38042. var bounciness = this.bounciness;
  38043. if (bounciness <= 1.0) {
  38044. bounciness = 1.001;
  38045. }
  38046. var num9 = Math.pow(bounciness, y);
  38047. var num5 = 1.0 - bounciness;
  38048. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  38049. var num15 = gradient * num4;
  38050. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  38051. var num3 = Math.floor(num65);
  38052. var num13 = num3 + 1.0;
  38053. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  38054. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  38055. var num7 = (num8 + num12) * 0.5;
  38056. var num6 = gradient - num7;
  38057. var num2 = num7 - num8;
  38058. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  38059. };
  38060. return BounceEase;
  38061. }(EasingFunction));
  38062. BABYLON.BounceEase = BounceEase;
  38063. var CubicEase = (function (_super) {
  38064. __extends(CubicEase, _super);
  38065. function CubicEase() {
  38066. return _super !== null && _super.apply(this, arguments) || this;
  38067. }
  38068. CubicEase.prototype.easeInCore = function (gradient) {
  38069. return (gradient * gradient * gradient);
  38070. };
  38071. return CubicEase;
  38072. }(EasingFunction));
  38073. BABYLON.CubicEase = CubicEase;
  38074. var ElasticEase = (function (_super) {
  38075. __extends(ElasticEase, _super);
  38076. function ElasticEase(oscillations, springiness) {
  38077. if (oscillations === void 0) { oscillations = 3; }
  38078. if (springiness === void 0) { springiness = 3; }
  38079. var _this = _super.call(this) || this;
  38080. _this.oscillations = oscillations;
  38081. _this.springiness = springiness;
  38082. return _this;
  38083. }
  38084. ElasticEase.prototype.easeInCore = function (gradient) {
  38085. var num2;
  38086. var num3 = Math.max(0.0, this.oscillations);
  38087. var num = Math.max(0.0, this.springiness);
  38088. if (num == 0) {
  38089. num2 = gradient;
  38090. }
  38091. else {
  38092. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  38093. }
  38094. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  38095. };
  38096. return ElasticEase;
  38097. }(EasingFunction));
  38098. BABYLON.ElasticEase = ElasticEase;
  38099. var ExponentialEase = (function (_super) {
  38100. __extends(ExponentialEase, _super);
  38101. function ExponentialEase(exponent) {
  38102. if (exponent === void 0) { exponent = 2; }
  38103. var _this = _super.call(this) || this;
  38104. _this.exponent = exponent;
  38105. return _this;
  38106. }
  38107. ExponentialEase.prototype.easeInCore = function (gradient) {
  38108. if (this.exponent <= 0) {
  38109. return gradient;
  38110. }
  38111. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  38112. };
  38113. return ExponentialEase;
  38114. }(EasingFunction));
  38115. BABYLON.ExponentialEase = ExponentialEase;
  38116. var PowerEase = (function (_super) {
  38117. __extends(PowerEase, _super);
  38118. function PowerEase(power) {
  38119. if (power === void 0) { power = 2; }
  38120. var _this = _super.call(this) || this;
  38121. _this.power = power;
  38122. return _this;
  38123. }
  38124. PowerEase.prototype.easeInCore = function (gradient) {
  38125. var y = Math.max(0.0, this.power);
  38126. return Math.pow(gradient, y);
  38127. };
  38128. return PowerEase;
  38129. }(EasingFunction));
  38130. BABYLON.PowerEase = PowerEase;
  38131. var QuadraticEase = (function (_super) {
  38132. __extends(QuadraticEase, _super);
  38133. function QuadraticEase() {
  38134. return _super !== null && _super.apply(this, arguments) || this;
  38135. }
  38136. QuadraticEase.prototype.easeInCore = function (gradient) {
  38137. return (gradient * gradient);
  38138. };
  38139. return QuadraticEase;
  38140. }(EasingFunction));
  38141. BABYLON.QuadraticEase = QuadraticEase;
  38142. var QuarticEase = (function (_super) {
  38143. __extends(QuarticEase, _super);
  38144. function QuarticEase() {
  38145. return _super !== null && _super.apply(this, arguments) || this;
  38146. }
  38147. QuarticEase.prototype.easeInCore = function (gradient) {
  38148. return (gradient * gradient * gradient * gradient);
  38149. };
  38150. return QuarticEase;
  38151. }(EasingFunction));
  38152. BABYLON.QuarticEase = QuarticEase;
  38153. var QuinticEase = (function (_super) {
  38154. __extends(QuinticEase, _super);
  38155. function QuinticEase() {
  38156. return _super !== null && _super.apply(this, arguments) || this;
  38157. }
  38158. QuinticEase.prototype.easeInCore = function (gradient) {
  38159. return (gradient * gradient * gradient * gradient * gradient);
  38160. };
  38161. return QuinticEase;
  38162. }(EasingFunction));
  38163. BABYLON.QuinticEase = QuinticEase;
  38164. var SineEase = (function (_super) {
  38165. __extends(SineEase, _super);
  38166. function SineEase() {
  38167. return _super !== null && _super.apply(this, arguments) || this;
  38168. }
  38169. SineEase.prototype.easeInCore = function (gradient) {
  38170. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  38171. };
  38172. return SineEase;
  38173. }(EasingFunction));
  38174. BABYLON.SineEase = SineEase;
  38175. var BezierCurveEase = (function (_super) {
  38176. __extends(BezierCurveEase, _super);
  38177. function BezierCurveEase(x1, y1, x2, y2) {
  38178. if (x1 === void 0) { x1 = 0; }
  38179. if (y1 === void 0) { y1 = 0; }
  38180. if (x2 === void 0) { x2 = 1; }
  38181. if (y2 === void 0) { y2 = 1; }
  38182. var _this = _super.call(this) || this;
  38183. _this.x1 = x1;
  38184. _this.y1 = y1;
  38185. _this.x2 = x2;
  38186. _this.y2 = y2;
  38187. return _this;
  38188. }
  38189. BezierCurveEase.prototype.easeInCore = function (gradient) {
  38190. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  38191. };
  38192. return BezierCurveEase;
  38193. }(EasingFunction));
  38194. BABYLON.BezierCurveEase = BezierCurveEase;
  38195. })(BABYLON || (BABYLON = {}));
  38196. //# sourceMappingURL=babylon.easing.js.map
  38197. var BABYLON;
  38198. (function (BABYLON) {
  38199. var Condition = (function () {
  38200. function Condition(actionManager) {
  38201. this._actionManager = actionManager;
  38202. }
  38203. Condition.prototype.isValid = function () {
  38204. return true;
  38205. };
  38206. Condition.prototype._getProperty = function (propertyPath) {
  38207. return this._actionManager._getProperty(propertyPath);
  38208. };
  38209. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38210. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38211. };
  38212. Condition.prototype.serialize = function () {
  38213. };
  38214. Condition.prototype._serialize = function (serializedCondition) {
  38215. return {
  38216. type: 2,
  38217. children: [],
  38218. name: serializedCondition.name,
  38219. properties: serializedCondition.properties
  38220. };
  38221. };
  38222. return Condition;
  38223. }());
  38224. BABYLON.Condition = Condition;
  38225. var ValueCondition = (function (_super) {
  38226. __extends(ValueCondition, _super);
  38227. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38228. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38229. var _this = _super.call(this, actionManager) || this;
  38230. _this.propertyPath = propertyPath;
  38231. _this.value = value;
  38232. _this.operator = operator;
  38233. _this._target = target;
  38234. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38235. _this._property = _this._getProperty(_this.propertyPath);
  38236. return _this;
  38237. }
  38238. Object.defineProperty(ValueCondition, "IsEqual", {
  38239. get: function () {
  38240. return ValueCondition._IsEqual;
  38241. },
  38242. enumerable: true,
  38243. configurable: true
  38244. });
  38245. Object.defineProperty(ValueCondition, "IsDifferent", {
  38246. get: function () {
  38247. return ValueCondition._IsDifferent;
  38248. },
  38249. enumerable: true,
  38250. configurable: true
  38251. });
  38252. Object.defineProperty(ValueCondition, "IsGreater", {
  38253. get: function () {
  38254. return ValueCondition._IsGreater;
  38255. },
  38256. enumerable: true,
  38257. configurable: true
  38258. });
  38259. Object.defineProperty(ValueCondition, "IsLesser", {
  38260. get: function () {
  38261. return ValueCondition._IsLesser;
  38262. },
  38263. enumerable: true,
  38264. configurable: true
  38265. });
  38266. // Methods
  38267. ValueCondition.prototype.isValid = function () {
  38268. switch (this.operator) {
  38269. case ValueCondition.IsGreater:
  38270. return this._effectiveTarget[this._property] > this.value;
  38271. case ValueCondition.IsLesser:
  38272. return this._effectiveTarget[this._property] < this.value;
  38273. case ValueCondition.IsEqual:
  38274. case ValueCondition.IsDifferent:
  38275. var check;
  38276. if (this.value.equals) {
  38277. check = this.value.equals(this._effectiveTarget[this._property]);
  38278. }
  38279. else {
  38280. check = this.value === this._effectiveTarget[this._property];
  38281. }
  38282. return this.operator === ValueCondition.IsEqual ? check : !check;
  38283. }
  38284. return false;
  38285. };
  38286. ValueCondition.prototype.serialize = function () {
  38287. return this._serialize({
  38288. name: "ValueCondition",
  38289. properties: [
  38290. BABYLON.Action._GetTargetProperty(this._target),
  38291. { name: "propertyPath", value: this.propertyPath },
  38292. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38293. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38294. ]
  38295. });
  38296. };
  38297. ValueCondition.GetOperatorName = function (operator) {
  38298. switch (operator) {
  38299. case ValueCondition._IsEqual: return "IsEqual";
  38300. case ValueCondition._IsDifferent: return "IsDifferent";
  38301. case ValueCondition._IsGreater: return "IsGreater";
  38302. case ValueCondition._IsLesser: return "IsLesser";
  38303. default: return "";
  38304. }
  38305. };
  38306. // Statics
  38307. ValueCondition._IsEqual = 0;
  38308. ValueCondition._IsDifferent = 1;
  38309. ValueCondition._IsGreater = 2;
  38310. ValueCondition._IsLesser = 3;
  38311. return ValueCondition;
  38312. }(Condition));
  38313. BABYLON.ValueCondition = ValueCondition;
  38314. var PredicateCondition = (function (_super) {
  38315. __extends(PredicateCondition, _super);
  38316. function PredicateCondition(actionManager, predicate) {
  38317. var _this = _super.call(this, actionManager) || this;
  38318. _this.predicate = predicate;
  38319. return _this;
  38320. }
  38321. PredicateCondition.prototype.isValid = function () {
  38322. return this.predicate();
  38323. };
  38324. return PredicateCondition;
  38325. }(Condition));
  38326. BABYLON.PredicateCondition = PredicateCondition;
  38327. var StateCondition = (function (_super) {
  38328. __extends(StateCondition, _super);
  38329. function StateCondition(actionManager, target, value) {
  38330. var _this = _super.call(this, actionManager) || this;
  38331. _this.value = value;
  38332. _this._target = target;
  38333. return _this;
  38334. }
  38335. // Methods
  38336. StateCondition.prototype.isValid = function () {
  38337. return this._target.state === this.value;
  38338. };
  38339. StateCondition.prototype.serialize = function () {
  38340. return this._serialize({
  38341. name: "StateCondition",
  38342. properties: [
  38343. BABYLON.Action._GetTargetProperty(this._target),
  38344. { name: "value", value: this.value }
  38345. ]
  38346. });
  38347. };
  38348. return StateCondition;
  38349. }(Condition));
  38350. BABYLON.StateCondition = StateCondition;
  38351. })(BABYLON || (BABYLON = {}));
  38352. //# sourceMappingURL=babylon.condition.js.map
  38353. var BABYLON;
  38354. (function (BABYLON) {
  38355. var Action = (function () {
  38356. function Action(triggerOptions, condition) {
  38357. this.triggerOptions = triggerOptions;
  38358. if (triggerOptions.parameter) {
  38359. this.trigger = triggerOptions.trigger;
  38360. this._triggerParameter = triggerOptions.parameter;
  38361. }
  38362. else {
  38363. this.trigger = triggerOptions;
  38364. }
  38365. this._nextActiveAction = this;
  38366. this._condition = condition;
  38367. }
  38368. // Methods
  38369. Action.prototype._prepare = function () {
  38370. };
  38371. Action.prototype.getTriggerParameter = function () {
  38372. return this._triggerParameter;
  38373. };
  38374. Action.prototype._executeCurrent = function (evt) {
  38375. if (this._nextActiveAction._condition) {
  38376. var condition = this._nextActiveAction._condition;
  38377. var currentRenderId = this._actionManager.getScene().getRenderId();
  38378. // We cache the current evaluation for the current frame
  38379. if (condition._evaluationId === currentRenderId) {
  38380. if (!condition._currentResult) {
  38381. return;
  38382. }
  38383. }
  38384. else {
  38385. condition._evaluationId = currentRenderId;
  38386. if (!condition.isValid()) {
  38387. condition._currentResult = false;
  38388. return;
  38389. }
  38390. condition._currentResult = true;
  38391. }
  38392. }
  38393. this._nextActiveAction.execute(evt);
  38394. this.skipToNextActiveAction();
  38395. };
  38396. Action.prototype.execute = function (evt) {
  38397. };
  38398. Action.prototype.skipToNextActiveAction = function () {
  38399. if (this._nextActiveAction._child) {
  38400. if (!this._nextActiveAction._child._actionManager) {
  38401. this._nextActiveAction._child._actionManager = this._actionManager;
  38402. }
  38403. this._nextActiveAction = this._nextActiveAction._child;
  38404. }
  38405. else {
  38406. this._nextActiveAction = this;
  38407. }
  38408. };
  38409. Action.prototype.then = function (action) {
  38410. this._child = action;
  38411. action._actionManager = this._actionManager;
  38412. action._prepare();
  38413. return action;
  38414. };
  38415. Action.prototype._getProperty = function (propertyPath) {
  38416. return this._actionManager._getProperty(propertyPath);
  38417. };
  38418. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  38419. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38420. };
  38421. Action.prototype.serialize = function (parent) {
  38422. };
  38423. // Called by BABYLON.Action objects in serialize(...). Internal use
  38424. Action.prototype._serialize = function (serializedAction, parent) {
  38425. var serializationObject = {
  38426. type: 1,
  38427. children: [],
  38428. name: serializedAction.name,
  38429. properties: serializedAction.properties || []
  38430. };
  38431. // Serialize child
  38432. if (this._child) {
  38433. this._child.serialize(serializationObject);
  38434. }
  38435. // Check if "this" has a condition
  38436. if (this._condition) {
  38437. var serializedCondition = this._condition.serialize();
  38438. serializedCondition.children.push(serializationObject);
  38439. if (parent) {
  38440. parent.children.push(serializedCondition);
  38441. }
  38442. return serializedCondition;
  38443. }
  38444. if (parent) {
  38445. parent.children.push(serializationObject);
  38446. }
  38447. return serializationObject;
  38448. };
  38449. Action._SerializeValueAsString = function (value) {
  38450. if (typeof value === "number") {
  38451. return value.toString();
  38452. }
  38453. if (typeof value === "boolean") {
  38454. return value ? "true" : "false";
  38455. }
  38456. if (value instanceof BABYLON.Vector2) {
  38457. return value.x + ", " + value.y;
  38458. }
  38459. if (value instanceof BABYLON.Vector3) {
  38460. return value.x + ", " + value.y + ", " + value.z;
  38461. }
  38462. if (value instanceof BABYLON.Color3) {
  38463. return value.r + ", " + value.g + ", " + value.b;
  38464. }
  38465. if (value instanceof BABYLON.Color4) {
  38466. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  38467. }
  38468. return value; // string
  38469. };
  38470. Action._GetTargetProperty = function (target) {
  38471. return {
  38472. name: "target",
  38473. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  38474. : target instanceof BABYLON.Light ? "LightProperties"
  38475. : target instanceof BABYLON.Camera ? "CameraProperties"
  38476. : "SceneProperties",
  38477. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  38478. };
  38479. };
  38480. return Action;
  38481. }());
  38482. BABYLON.Action = Action;
  38483. })(BABYLON || (BABYLON = {}));
  38484. //# sourceMappingURL=babylon.action.js.map
  38485. var BABYLON;
  38486. (function (BABYLON) {
  38487. /**
  38488. * ActionEvent is the event beint sent when an action is triggered.
  38489. */
  38490. var ActionEvent = (function () {
  38491. /**
  38492. * @param source The mesh or sprite that triggered the action.
  38493. * @param pointerX The X mouse cursor position at the time of the event
  38494. * @param pointerY The Y mouse cursor position at the time of the event
  38495. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  38496. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  38497. */
  38498. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  38499. this.source = source;
  38500. this.pointerX = pointerX;
  38501. this.pointerY = pointerY;
  38502. this.meshUnderPointer = meshUnderPointer;
  38503. this.sourceEvent = sourceEvent;
  38504. this.additionalData = additionalData;
  38505. }
  38506. /**
  38507. * Helper function to auto-create an ActionEvent from a source mesh.
  38508. * @param source The source mesh that triggered the event
  38509. * @param evt {Event} The original (browser) event
  38510. */
  38511. ActionEvent.CreateNew = function (source, evt, additionalData) {
  38512. var scene = source.getScene();
  38513. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38514. };
  38515. /**
  38516. * Helper function to auto-create an ActionEvent from a source mesh.
  38517. * @param source The source sprite that triggered the event
  38518. * @param scene Scene associated with the sprite
  38519. * @param evt {Event} The original (browser) event
  38520. */
  38521. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  38522. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38523. };
  38524. /**
  38525. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  38526. * @param scene the scene where the event occurred
  38527. * @param evt {Event} The original (browser) event
  38528. */
  38529. ActionEvent.CreateNewFromScene = function (scene, evt) {
  38530. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  38531. };
  38532. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  38533. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  38534. };
  38535. return ActionEvent;
  38536. }());
  38537. BABYLON.ActionEvent = ActionEvent;
  38538. /**
  38539. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38540. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38541. */
  38542. var ActionManager = (function () {
  38543. function ActionManager(scene) {
  38544. // Members
  38545. this.actions = new Array();
  38546. this.hoverCursor = '';
  38547. this._scene = scene;
  38548. scene._actionManagers.push(this);
  38549. }
  38550. Object.defineProperty(ActionManager, "NothingTrigger", {
  38551. get: function () {
  38552. return ActionManager._NothingTrigger;
  38553. },
  38554. enumerable: true,
  38555. configurable: true
  38556. });
  38557. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38558. get: function () {
  38559. return ActionManager._OnPickTrigger;
  38560. },
  38561. enumerable: true,
  38562. configurable: true
  38563. });
  38564. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38565. get: function () {
  38566. return ActionManager._OnLeftPickTrigger;
  38567. },
  38568. enumerable: true,
  38569. configurable: true
  38570. });
  38571. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38572. get: function () {
  38573. return ActionManager._OnRightPickTrigger;
  38574. },
  38575. enumerable: true,
  38576. configurable: true
  38577. });
  38578. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38579. get: function () {
  38580. return ActionManager._OnCenterPickTrigger;
  38581. },
  38582. enumerable: true,
  38583. configurable: true
  38584. });
  38585. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38586. get: function () {
  38587. return ActionManager._OnPickDownTrigger;
  38588. },
  38589. enumerable: true,
  38590. configurable: true
  38591. });
  38592. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  38593. get: function () {
  38594. return ActionManager._OnDoublePickTrigger;
  38595. },
  38596. enumerable: true,
  38597. configurable: true
  38598. });
  38599. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38600. get: function () {
  38601. return ActionManager._OnPickUpTrigger;
  38602. },
  38603. enumerable: true,
  38604. configurable: true
  38605. });
  38606. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38607. /// This trigger will only be raised if you also declared a OnPickDown
  38608. get: function () {
  38609. return ActionManager._OnPickOutTrigger;
  38610. },
  38611. enumerable: true,
  38612. configurable: true
  38613. });
  38614. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38615. get: function () {
  38616. return ActionManager._OnLongPressTrigger;
  38617. },
  38618. enumerable: true,
  38619. configurable: true
  38620. });
  38621. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38622. get: function () {
  38623. return ActionManager._OnPointerOverTrigger;
  38624. },
  38625. enumerable: true,
  38626. configurable: true
  38627. });
  38628. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38629. get: function () {
  38630. return ActionManager._OnPointerOutTrigger;
  38631. },
  38632. enumerable: true,
  38633. configurable: true
  38634. });
  38635. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38636. get: function () {
  38637. return ActionManager._OnEveryFrameTrigger;
  38638. },
  38639. enumerable: true,
  38640. configurable: true
  38641. });
  38642. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38643. get: function () {
  38644. return ActionManager._OnIntersectionEnterTrigger;
  38645. },
  38646. enumerable: true,
  38647. configurable: true
  38648. });
  38649. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38650. get: function () {
  38651. return ActionManager._OnIntersectionExitTrigger;
  38652. },
  38653. enumerable: true,
  38654. configurable: true
  38655. });
  38656. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38657. get: function () {
  38658. return ActionManager._OnKeyDownTrigger;
  38659. },
  38660. enumerable: true,
  38661. configurable: true
  38662. });
  38663. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38664. get: function () {
  38665. return ActionManager._OnKeyUpTrigger;
  38666. },
  38667. enumerable: true,
  38668. configurable: true
  38669. });
  38670. // Methods
  38671. ActionManager.prototype.dispose = function () {
  38672. var index = this._scene._actionManagers.indexOf(this);
  38673. for (var i = 0; i < this.actions.length; i++) {
  38674. var action = this.actions[i];
  38675. ActionManager.Triggers[action.trigger]--;
  38676. if (ActionManager.Triggers[action.trigger] === 0) {
  38677. delete ActionManager.Triggers[action.trigger];
  38678. }
  38679. }
  38680. if (index > -1) {
  38681. this._scene._actionManagers.splice(index, 1);
  38682. }
  38683. };
  38684. ActionManager.prototype.getScene = function () {
  38685. return this._scene;
  38686. };
  38687. /**
  38688. * Does this action manager handles actions of any of the given triggers
  38689. * @param {number[]} triggers - the triggers to be tested
  38690. * @return {boolean} whether one (or more) of the triggers is handeled
  38691. */
  38692. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38693. for (var index = 0; index < this.actions.length; index++) {
  38694. var action = this.actions[index];
  38695. if (triggers.indexOf(action.trigger) > -1) {
  38696. return true;
  38697. }
  38698. }
  38699. return false;
  38700. };
  38701. /**
  38702. * Does this action manager handles actions of a given trigger
  38703. * @param {number} trigger - the trigger to be tested
  38704. * @return {boolean} whether the trigger is handeled
  38705. */
  38706. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38707. for (var index = 0; index < this.actions.length; index++) {
  38708. var action = this.actions[index];
  38709. if (action.trigger === trigger) {
  38710. return true;
  38711. }
  38712. }
  38713. return false;
  38714. };
  38715. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38716. /**
  38717. * Does this action manager has pointer triggers
  38718. * @return {boolean} whether or not it has pointer triggers
  38719. */
  38720. get: function () {
  38721. for (var index = 0; index < this.actions.length; index++) {
  38722. var action = this.actions[index];
  38723. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38724. return true;
  38725. }
  38726. }
  38727. return false;
  38728. },
  38729. enumerable: true,
  38730. configurable: true
  38731. });
  38732. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38733. /**
  38734. * Does this action manager has pick triggers
  38735. * @return {boolean} whether or not it has pick triggers
  38736. */
  38737. get: function () {
  38738. for (var index = 0; index < this.actions.length; index++) {
  38739. var action = this.actions[index];
  38740. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38741. return true;
  38742. }
  38743. }
  38744. return false;
  38745. },
  38746. enumerable: true,
  38747. configurable: true
  38748. });
  38749. Object.defineProperty(ActionManager, "HasTriggers", {
  38750. /**
  38751. * Does exist one action manager with at least one trigger
  38752. * @return {boolean} whether or not it exists one action manager with one trigger
  38753. **/
  38754. get: function () {
  38755. for (var t in ActionManager.Triggers) {
  38756. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38757. return true;
  38758. }
  38759. }
  38760. return false;
  38761. },
  38762. enumerable: true,
  38763. configurable: true
  38764. });
  38765. Object.defineProperty(ActionManager, "HasPickTriggers", {
  38766. /**
  38767. * Does exist one action manager with at least one pick trigger
  38768. * @return {boolean} whether or not it exists one action manager with one pick trigger
  38769. **/
  38770. get: function () {
  38771. for (var t in ActionManager.Triggers) {
  38772. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38773. var t_int = parseInt(t);
  38774. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  38775. return true;
  38776. }
  38777. }
  38778. }
  38779. return false;
  38780. },
  38781. enumerable: true,
  38782. configurable: true
  38783. });
  38784. /**
  38785. * Does exist one action manager that handles actions of a given trigger
  38786. * @param {number} trigger - the trigger to be tested
  38787. * @return {boolean} whether the trigger is handeled by at least one action manager
  38788. **/
  38789. ActionManager.HasSpecificTrigger = function (trigger) {
  38790. for (var t in ActionManager.Triggers) {
  38791. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38792. var t_int = parseInt(t);
  38793. if (t_int === trigger) {
  38794. return true;
  38795. }
  38796. }
  38797. }
  38798. return false;
  38799. };
  38800. /**
  38801. * Registers an action to this action manager
  38802. * @param {BABYLON.Action} action - the action to be registered
  38803. * @return {BABYLON.Action} the action amended (prepared) after registration
  38804. */
  38805. ActionManager.prototype.registerAction = function (action) {
  38806. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38807. if (this.getScene().actionManager !== this) {
  38808. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38809. return null;
  38810. }
  38811. }
  38812. this.actions.push(action);
  38813. if (ActionManager.Triggers[action.trigger]) {
  38814. ActionManager.Triggers[action.trigger]++;
  38815. }
  38816. else {
  38817. ActionManager.Triggers[action.trigger] = 1;
  38818. }
  38819. action._actionManager = this;
  38820. action._prepare();
  38821. return action;
  38822. };
  38823. /**
  38824. * Process a specific trigger
  38825. * @param {number} trigger - the trigger to process
  38826. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38827. */
  38828. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38829. for (var index = 0; index < this.actions.length; index++) {
  38830. var action = this.actions[index];
  38831. if (action.trigger === trigger) {
  38832. if (trigger === ActionManager.OnKeyUpTrigger
  38833. || trigger === ActionManager.OnKeyDownTrigger) {
  38834. var parameter = action.getTriggerParameter();
  38835. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38836. if (!parameter.toLowerCase) {
  38837. continue;
  38838. }
  38839. var lowerCase = parameter.toLowerCase();
  38840. if (lowerCase !== evt.sourceEvent.key) {
  38841. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38842. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38843. if (actualkey !== lowerCase) {
  38844. continue;
  38845. }
  38846. }
  38847. }
  38848. }
  38849. action._executeCurrent(evt);
  38850. }
  38851. }
  38852. };
  38853. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38854. var properties = propertyPath.split(".");
  38855. for (var index = 0; index < properties.length - 1; index++) {
  38856. target = target[properties[index]];
  38857. }
  38858. return target;
  38859. };
  38860. ActionManager.prototype._getProperty = function (propertyPath) {
  38861. var properties = propertyPath.split(".");
  38862. return properties[properties.length - 1];
  38863. };
  38864. ActionManager.prototype.serialize = function (name) {
  38865. var root = {
  38866. children: [],
  38867. name: name,
  38868. type: 3,
  38869. properties: [] // Empty for root but required
  38870. };
  38871. for (var i = 0; i < this.actions.length; i++) {
  38872. var triggerObject = {
  38873. type: 0,
  38874. children: [],
  38875. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38876. properties: []
  38877. };
  38878. var triggerOptions = this.actions[i].triggerOptions;
  38879. if (triggerOptions && typeof triggerOptions !== "number") {
  38880. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38881. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38882. }
  38883. else {
  38884. var parameter = {};
  38885. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38886. if (triggerOptions.parameter.mesh) {
  38887. parameter._meshId = triggerOptions.parameter.mesh.id;
  38888. }
  38889. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38890. }
  38891. }
  38892. // Serialize child action, recursively
  38893. this.actions[i].serialize(triggerObject);
  38894. // Add serialized trigger
  38895. root.children.push(triggerObject);
  38896. }
  38897. return root;
  38898. };
  38899. ActionManager.Parse = function (parsedActions, object, scene) {
  38900. var actionManager = new BABYLON.ActionManager(scene);
  38901. if (object === null)
  38902. scene.actionManager = actionManager;
  38903. else
  38904. object.actionManager = actionManager;
  38905. // instanciate a new object
  38906. var instanciate = function (name, params) {
  38907. var newInstance = Object.create(BABYLON[name].prototype);
  38908. newInstance.constructor.apply(newInstance, params);
  38909. return newInstance;
  38910. };
  38911. var parseParameter = function (name, value, target, propertyPath) {
  38912. if (propertyPath === null) {
  38913. // String, boolean or float
  38914. var floatValue = parseFloat(value);
  38915. if (value === "true" || value === "false")
  38916. return value === "true";
  38917. else
  38918. return isNaN(floatValue) ? value : floatValue;
  38919. }
  38920. var effectiveTarget = propertyPath.split(".");
  38921. var values = value.split(",");
  38922. // Get effective Target
  38923. for (var i = 0; i < effectiveTarget.length; i++) {
  38924. target = target[effectiveTarget[i]];
  38925. }
  38926. // Return appropriate value with its type
  38927. if (typeof (target) === "boolean")
  38928. return values[0] === "true";
  38929. if (typeof (target) === "string")
  38930. return values[0];
  38931. // Parameters with multiple values such as Vector3 etc.
  38932. var split = new Array();
  38933. for (var i = 0; i < values.length; i++)
  38934. split.push(parseFloat(values[i]));
  38935. if (target instanceof BABYLON.Vector3)
  38936. return BABYLON.Vector3.FromArray(split);
  38937. if (target instanceof BABYLON.Vector4)
  38938. return BABYLON.Vector4.FromArray(split);
  38939. if (target instanceof BABYLON.Color3)
  38940. return BABYLON.Color3.FromArray(split);
  38941. if (target instanceof BABYLON.Color4)
  38942. return BABYLON.Color4.FromArray(split);
  38943. return parseFloat(values[0]);
  38944. };
  38945. // traverse graph per trigger
  38946. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  38947. if (combineArray === void 0) { combineArray = null; }
  38948. if (parsedAction.detached)
  38949. return;
  38950. var parameters = new Array();
  38951. var target = null;
  38952. var propertyPath = null;
  38953. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  38954. // Parameters
  38955. if (parsedAction.type === 2)
  38956. parameters.push(actionManager);
  38957. else
  38958. parameters.push(trigger);
  38959. if (combine) {
  38960. var actions = new Array();
  38961. for (var j = 0; j < parsedAction.combine.length; j++) {
  38962. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  38963. }
  38964. parameters.push(actions);
  38965. }
  38966. else {
  38967. for (var i = 0; i < parsedAction.properties.length; i++) {
  38968. var value = parsedAction.properties[i].value;
  38969. var name = parsedAction.properties[i].name;
  38970. var targetType = parsedAction.properties[i].targetType;
  38971. if (name === "target")
  38972. if (targetType !== null && targetType === "SceneProperties")
  38973. value = target = scene;
  38974. else
  38975. value = target = scene.getNodeByName(value);
  38976. else if (name === "parent")
  38977. value = scene.getNodeByName(value);
  38978. else if (name === "sound")
  38979. value = scene.getSoundByName(value);
  38980. else if (name !== "propertyPath") {
  38981. if (parsedAction.type === 2 && name === "operator")
  38982. value = BABYLON.ValueCondition[value];
  38983. else
  38984. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  38985. }
  38986. else {
  38987. propertyPath = value;
  38988. }
  38989. parameters.push(value);
  38990. }
  38991. }
  38992. if (combineArray === null) {
  38993. parameters.push(condition);
  38994. }
  38995. else {
  38996. parameters.push(null);
  38997. }
  38998. // If interpolate value action
  38999. if (parsedAction.name === "InterpolateValueAction") {
  39000. var param = parameters[parameters.length - 2];
  39001. parameters[parameters.length - 1] = param;
  39002. parameters[parameters.length - 2] = condition;
  39003. }
  39004. // Action or condition(s) and not CombineAction
  39005. var newAction = instanciate(parsedAction.name, parameters);
  39006. if (newAction instanceof BABYLON.Condition && condition !== null) {
  39007. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  39008. if (action)
  39009. action.then(nothing);
  39010. else
  39011. actionManager.registerAction(nothing);
  39012. action = nothing;
  39013. }
  39014. if (combineArray === null) {
  39015. if (newAction instanceof BABYLON.Condition) {
  39016. condition = newAction;
  39017. newAction = action;
  39018. }
  39019. else {
  39020. condition = null;
  39021. if (action)
  39022. action.then(newAction);
  39023. else
  39024. actionManager.registerAction(newAction);
  39025. }
  39026. }
  39027. else {
  39028. combineArray.push(newAction);
  39029. }
  39030. for (var i = 0; i < parsedAction.children.length; i++)
  39031. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  39032. };
  39033. // triggers
  39034. for (var i = 0; i < parsedActions.children.length; i++) {
  39035. var triggerParams;
  39036. var trigger = parsedActions.children[i];
  39037. if (trigger.properties.length > 0) {
  39038. var param = trigger.properties[0].value;
  39039. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  39040. if (value._meshId) {
  39041. value.mesh = scene.getMeshByID(value._meshId);
  39042. }
  39043. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  39044. }
  39045. else
  39046. triggerParams = BABYLON.ActionManager[trigger.name];
  39047. for (var j = 0; j < trigger.children.length; j++) {
  39048. if (!trigger.detached)
  39049. traverse(trigger.children[j], triggerParams, null, null);
  39050. }
  39051. }
  39052. };
  39053. ActionManager.GetTriggerName = function (trigger) {
  39054. switch (trigger) {
  39055. case 0: return "NothingTrigger";
  39056. case 1: return "OnPickTrigger";
  39057. case 2: return "OnLeftPickTrigger";
  39058. case 3: return "OnRightPickTrigger";
  39059. case 4: return "OnCenterPickTrigger";
  39060. case 5: return "OnPickDownTrigger";
  39061. case 6: return "OnPickUpTrigger";
  39062. case 7: return "OnLongPressTrigger";
  39063. case 8: return "OnPointerOverTrigger";
  39064. case 9: return "OnPointerOutTrigger";
  39065. case 10: return "OnEveryFrameTrigger";
  39066. case 11: return "OnIntersectionEnterTrigger";
  39067. case 12: return "OnIntersectionExitTrigger";
  39068. case 13: return "OnKeyDownTrigger";
  39069. case 14: return "OnKeyUpTrigger";
  39070. case 15: return "OnPickOutTrigger";
  39071. default: return "";
  39072. }
  39073. };
  39074. // Statics
  39075. ActionManager._NothingTrigger = 0;
  39076. ActionManager._OnPickTrigger = 1;
  39077. ActionManager._OnLeftPickTrigger = 2;
  39078. ActionManager._OnRightPickTrigger = 3;
  39079. ActionManager._OnCenterPickTrigger = 4;
  39080. ActionManager._OnPickDownTrigger = 5;
  39081. ActionManager._OnDoublePickTrigger = 6;
  39082. ActionManager._OnPickUpTrigger = 7;
  39083. ActionManager._OnLongPressTrigger = 8;
  39084. ActionManager._OnPointerOverTrigger = 9;
  39085. ActionManager._OnPointerOutTrigger = 10;
  39086. ActionManager._OnEveryFrameTrigger = 11;
  39087. ActionManager._OnIntersectionEnterTrigger = 12;
  39088. ActionManager._OnIntersectionExitTrigger = 13;
  39089. ActionManager._OnKeyDownTrigger = 14;
  39090. ActionManager._OnKeyUpTrigger = 15;
  39091. ActionManager._OnPickOutTrigger = 16;
  39092. ActionManager.Triggers = {};
  39093. return ActionManager;
  39094. }());
  39095. BABYLON.ActionManager = ActionManager;
  39096. })(BABYLON || (BABYLON = {}));
  39097. //# sourceMappingURL=babylon.actionManager.js.map
  39098. var BABYLON;
  39099. (function (BABYLON) {
  39100. var InterpolateValueAction = (function (_super) {
  39101. __extends(InterpolateValueAction, _super);
  39102. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  39103. if (duration === void 0) { duration = 1000; }
  39104. var _this = _super.call(this, triggerOptions, condition) || this;
  39105. _this.propertyPath = propertyPath;
  39106. _this.value = value;
  39107. _this.duration = duration;
  39108. _this.stopOtherAnimations = stopOtherAnimations;
  39109. _this.onInterpolationDone = onInterpolationDone;
  39110. _this._target = _this._effectiveTarget = target;
  39111. return _this;
  39112. }
  39113. InterpolateValueAction.prototype._prepare = function () {
  39114. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39115. this._property = this._getProperty(this.propertyPath);
  39116. };
  39117. InterpolateValueAction.prototype.execute = function () {
  39118. var scene = this._actionManager.getScene();
  39119. var keys = [
  39120. {
  39121. frame: 0,
  39122. value: this._effectiveTarget[this._property]
  39123. }, {
  39124. frame: 100,
  39125. value: this.value
  39126. }
  39127. ];
  39128. var dataType;
  39129. if (typeof this.value === "number") {
  39130. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  39131. }
  39132. else if (this.value instanceof BABYLON.Color3) {
  39133. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  39134. }
  39135. else if (this.value instanceof BABYLON.Vector3) {
  39136. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  39137. }
  39138. else if (this.value instanceof BABYLON.Matrix) {
  39139. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  39140. }
  39141. else if (this.value instanceof BABYLON.Quaternion) {
  39142. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  39143. }
  39144. else {
  39145. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  39146. return;
  39147. }
  39148. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39149. animation.setKeys(keys);
  39150. if (this.stopOtherAnimations) {
  39151. scene.stopAnimation(this._effectiveTarget);
  39152. }
  39153. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  39154. };
  39155. InterpolateValueAction.prototype.serialize = function (parent) {
  39156. return _super.prototype._serialize.call(this, {
  39157. name: "InterpolateValueAction",
  39158. properties: [
  39159. BABYLON.Action._GetTargetProperty(this._target),
  39160. { name: "propertyPath", value: this.propertyPath },
  39161. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39162. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  39163. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  39164. ]
  39165. }, parent);
  39166. };
  39167. return InterpolateValueAction;
  39168. }(BABYLON.Action));
  39169. BABYLON.InterpolateValueAction = InterpolateValueAction;
  39170. })(BABYLON || (BABYLON = {}));
  39171. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  39172. var BABYLON;
  39173. (function (BABYLON) {
  39174. var SwitchBooleanAction = (function (_super) {
  39175. __extends(SwitchBooleanAction, _super);
  39176. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  39177. var _this = _super.call(this, triggerOptions, condition) || this;
  39178. _this.propertyPath = propertyPath;
  39179. _this._target = _this._effectiveTarget = target;
  39180. return _this;
  39181. }
  39182. SwitchBooleanAction.prototype._prepare = function () {
  39183. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39184. this._property = this._getProperty(this.propertyPath);
  39185. };
  39186. SwitchBooleanAction.prototype.execute = function () {
  39187. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  39188. };
  39189. SwitchBooleanAction.prototype.serialize = function (parent) {
  39190. return _super.prototype._serialize.call(this, {
  39191. name: "SwitchBooleanAction",
  39192. properties: [
  39193. BABYLON.Action._GetTargetProperty(this._target),
  39194. { name: "propertyPath", value: this.propertyPath }
  39195. ]
  39196. }, parent);
  39197. };
  39198. return SwitchBooleanAction;
  39199. }(BABYLON.Action));
  39200. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  39201. var SetStateAction = (function (_super) {
  39202. __extends(SetStateAction, _super);
  39203. function SetStateAction(triggerOptions, target, value, condition) {
  39204. var _this = _super.call(this, triggerOptions, condition) || this;
  39205. _this.value = value;
  39206. _this._target = target;
  39207. return _this;
  39208. }
  39209. SetStateAction.prototype.execute = function () {
  39210. this._target.state = this.value;
  39211. };
  39212. SetStateAction.prototype.serialize = function (parent) {
  39213. return _super.prototype._serialize.call(this, {
  39214. name: "SetStateAction",
  39215. properties: [
  39216. BABYLON.Action._GetTargetProperty(this._target),
  39217. { name: "value", value: this.value }
  39218. ]
  39219. }, parent);
  39220. };
  39221. return SetStateAction;
  39222. }(BABYLON.Action));
  39223. BABYLON.SetStateAction = SetStateAction;
  39224. var SetValueAction = (function (_super) {
  39225. __extends(SetValueAction, _super);
  39226. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39227. var _this = _super.call(this, triggerOptions, condition) || this;
  39228. _this.propertyPath = propertyPath;
  39229. _this.value = value;
  39230. _this._target = _this._effectiveTarget = target;
  39231. return _this;
  39232. }
  39233. SetValueAction.prototype._prepare = function () {
  39234. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39235. this._property = this._getProperty(this.propertyPath);
  39236. };
  39237. SetValueAction.prototype.execute = function () {
  39238. this._effectiveTarget[this._property] = this.value;
  39239. if (this._target.markAsDirty) {
  39240. this._target.markAsDirty(this._property);
  39241. }
  39242. };
  39243. SetValueAction.prototype.serialize = function (parent) {
  39244. return _super.prototype._serialize.call(this, {
  39245. name: "SetValueAction",
  39246. properties: [
  39247. BABYLON.Action._GetTargetProperty(this._target),
  39248. { name: "propertyPath", value: this.propertyPath },
  39249. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39250. ]
  39251. }, parent);
  39252. };
  39253. return SetValueAction;
  39254. }(BABYLON.Action));
  39255. BABYLON.SetValueAction = SetValueAction;
  39256. var IncrementValueAction = (function (_super) {
  39257. __extends(IncrementValueAction, _super);
  39258. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39259. var _this = _super.call(this, triggerOptions, condition) || this;
  39260. _this.propertyPath = propertyPath;
  39261. _this.value = value;
  39262. _this._target = _this._effectiveTarget = target;
  39263. return _this;
  39264. }
  39265. IncrementValueAction.prototype._prepare = function () {
  39266. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39267. this._property = this._getProperty(this.propertyPath);
  39268. if (typeof this._effectiveTarget[this._property] !== "number") {
  39269. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39270. }
  39271. };
  39272. IncrementValueAction.prototype.execute = function () {
  39273. this._effectiveTarget[this._property] += this.value;
  39274. if (this._target.markAsDirty) {
  39275. this._target.markAsDirty(this._property);
  39276. }
  39277. };
  39278. IncrementValueAction.prototype.serialize = function (parent) {
  39279. return _super.prototype._serialize.call(this, {
  39280. name: "IncrementValueAction",
  39281. properties: [
  39282. BABYLON.Action._GetTargetProperty(this._target),
  39283. { name: "propertyPath", value: this.propertyPath },
  39284. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39285. ]
  39286. }, parent);
  39287. };
  39288. return IncrementValueAction;
  39289. }(BABYLON.Action));
  39290. BABYLON.IncrementValueAction = IncrementValueAction;
  39291. var PlayAnimationAction = (function (_super) {
  39292. __extends(PlayAnimationAction, _super);
  39293. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39294. var _this = _super.call(this, triggerOptions, condition) || this;
  39295. _this.from = from;
  39296. _this.to = to;
  39297. _this.loop = loop;
  39298. _this._target = target;
  39299. return _this;
  39300. }
  39301. PlayAnimationAction.prototype._prepare = function () {
  39302. };
  39303. PlayAnimationAction.prototype.execute = function () {
  39304. var scene = this._actionManager.getScene();
  39305. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39306. };
  39307. PlayAnimationAction.prototype.serialize = function (parent) {
  39308. return _super.prototype._serialize.call(this, {
  39309. name: "PlayAnimationAction",
  39310. properties: [
  39311. BABYLON.Action._GetTargetProperty(this._target),
  39312. { name: "from", value: String(this.from) },
  39313. { name: "to", value: String(this.to) },
  39314. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39315. ]
  39316. }, parent);
  39317. };
  39318. return PlayAnimationAction;
  39319. }(BABYLON.Action));
  39320. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39321. var StopAnimationAction = (function (_super) {
  39322. __extends(StopAnimationAction, _super);
  39323. function StopAnimationAction(triggerOptions, target, condition) {
  39324. var _this = _super.call(this, triggerOptions, condition) || this;
  39325. _this._target = target;
  39326. return _this;
  39327. }
  39328. StopAnimationAction.prototype._prepare = function () {
  39329. };
  39330. StopAnimationAction.prototype.execute = function () {
  39331. var scene = this._actionManager.getScene();
  39332. scene.stopAnimation(this._target);
  39333. };
  39334. StopAnimationAction.prototype.serialize = function (parent) {
  39335. return _super.prototype._serialize.call(this, {
  39336. name: "StopAnimationAction",
  39337. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39338. }, parent);
  39339. };
  39340. return StopAnimationAction;
  39341. }(BABYLON.Action));
  39342. BABYLON.StopAnimationAction = StopAnimationAction;
  39343. var DoNothingAction = (function (_super) {
  39344. __extends(DoNothingAction, _super);
  39345. function DoNothingAction(triggerOptions, condition) {
  39346. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39347. return _super.call(this, triggerOptions, condition) || this;
  39348. }
  39349. DoNothingAction.prototype.execute = function () {
  39350. };
  39351. DoNothingAction.prototype.serialize = function (parent) {
  39352. return _super.prototype._serialize.call(this, {
  39353. name: "DoNothingAction",
  39354. properties: []
  39355. }, parent);
  39356. };
  39357. return DoNothingAction;
  39358. }(BABYLON.Action));
  39359. BABYLON.DoNothingAction = DoNothingAction;
  39360. var CombineAction = (function (_super) {
  39361. __extends(CombineAction, _super);
  39362. function CombineAction(triggerOptions, children, condition) {
  39363. var _this = _super.call(this, triggerOptions, condition) || this;
  39364. _this.children = children;
  39365. return _this;
  39366. }
  39367. CombineAction.prototype._prepare = function () {
  39368. for (var index = 0; index < this.children.length; index++) {
  39369. this.children[index]._actionManager = this._actionManager;
  39370. this.children[index]._prepare();
  39371. }
  39372. };
  39373. CombineAction.prototype.execute = function (evt) {
  39374. for (var index = 0; index < this.children.length; index++) {
  39375. this.children[index].execute(evt);
  39376. }
  39377. };
  39378. CombineAction.prototype.serialize = function (parent) {
  39379. var serializationObject = _super.prototype._serialize.call(this, {
  39380. name: "CombineAction",
  39381. properties: [],
  39382. combine: []
  39383. }, parent);
  39384. for (var i = 0; i < this.children.length; i++) {
  39385. serializationObject.combine.push(this.children[i].serialize(null));
  39386. }
  39387. return serializationObject;
  39388. };
  39389. return CombineAction;
  39390. }(BABYLON.Action));
  39391. BABYLON.CombineAction = CombineAction;
  39392. var ExecuteCodeAction = (function (_super) {
  39393. __extends(ExecuteCodeAction, _super);
  39394. function ExecuteCodeAction(triggerOptions, func, condition) {
  39395. var _this = _super.call(this, triggerOptions, condition) || this;
  39396. _this.func = func;
  39397. return _this;
  39398. }
  39399. ExecuteCodeAction.prototype.execute = function (evt) {
  39400. this.func(evt);
  39401. };
  39402. return ExecuteCodeAction;
  39403. }(BABYLON.Action));
  39404. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  39405. var SetParentAction = (function (_super) {
  39406. __extends(SetParentAction, _super);
  39407. function SetParentAction(triggerOptions, target, parent, condition) {
  39408. var _this = _super.call(this, triggerOptions, condition) || this;
  39409. _this._target = target;
  39410. _this._parent = parent;
  39411. return _this;
  39412. }
  39413. SetParentAction.prototype._prepare = function () {
  39414. };
  39415. SetParentAction.prototype.execute = function () {
  39416. if (this._target.parent === this._parent) {
  39417. return;
  39418. }
  39419. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  39420. invertParentWorldMatrix.invert();
  39421. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  39422. this._target.parent = this._parent;
  39423. };
  39424. SetParentAction.prototype.serialize = function (parent) {
  39425. return _super.prototype._serialize.call(this, {
  39426. name: "SetParentAction",
  39427. properties: [
  39428. BABYLON.Action._GetTargetProperty(this._target),
  39429. BABYLON.Action._GetTargetProperty(this._parent),
  39430. ]
  39431. }, parent);
  39432. };
  39433. return SetParentAction;
  39434. }(BABYLON.Action));
  39435. BABYLON.SetParentAction = SetParentAction;
  39436. var PlaySoundAction = (function (_super) {
  39437. __extends(PlaySoundAction, _super);
  39438. function PlaySoundAction(triggerOptions, sound, condition) {
  39439. var _this = _super.call(this, triggerOptions, condition) || this;
  39440. _this._sound = sound;
  39441. return _this;
  39442. }
  39443. PlaySoundAction.prototype._prepare = function () {
  39444. };
  39445. PlaySoundAction.prototype.execute = function () {
  39446. if (this._sound !== undefined)
  39447. this._sound.play();
  39448. };
  39449. PlaySoundAction.prototype.serialize = function (parent) {
  39450. return _super.prototype._serialize.call(this, {
  39451. name: "PlaySoundAction",
  39452. properties: [{ name: "sound", value: this._sound.name }]
  39453. }, parent);
  39454. };
  39455. return PlaySoundAction;
  39456. }(BABYLON.Action));
  39457. BABYLON.PlaySoundAction = PlaySoundAction;
  39458. var StopSoundAction = (function (_super) {
  39459. __extends(StopSoundAction, _super);
  39460. function StopSoundAction(triggerOptions, sound, condition) {
  39461. var _this = _super.call(this, triggerOptions, condition) || this;
  39462. _this._sound = sound;
  39463. return _this;
  39464. }
  39465. StopSoundAction.prototype._prepare = function () {
  39466. };
  39467. StopSoundAction.prototype.execute = function () {
  39468. if (this._sound !== undefined)
  39469. this._sound.stop();
  39470. };
  39471. StopSoundAction.prototype.serialize = function (parent) {
  39472. return _super.prototype._serialize.call(this, {
  39473. name: "StopSoundAction",
  39474. properties: [{ name: "sound", value: this._sound.name }]
  39475. }, parent);
  39476. };
  39477. return StopSoundAction;
  39478. }(BABYLON.Action));
  39479. BABYLON.StopSoundAction = StopSoundAction;
  39480. })(BABYLON || (BABYLON = {}));
  39481. //# sourceMappingURL=babylon.directActions.js.map
  39482. var BABYLON;
  39483. (function (BABYLON) {
  39484. var SpriteManager = (function () {
  39485. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  39486. if (epsilon === void 0) { epsilon = 0.01; }
  39487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39488. this.name = name;
  39489. this.sprites = new Array();
  39490. this.renderingGroupId = 0;
  39491. this.layerMask = 0x0FFFFFFF;
  39492. this.fogEnabled = true;
  39493. this.isPickable = false;
  39494. /**
  39495. * An event triggered when the manager is disposed.
  39496. * @type {BABYLON.Observable}
  39497. */
  39498. this.onDisposeObservable = new BABYLON.Observable();
  39499. this._vertexBuffers = {};
  39500. this._capacity = capacity;
  39501. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  39502. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39503. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39504. if (cellSize.width && cellSize.height) {
  39505. this.cellWidth = cellSize.width;
  39506. this.cellHeight = cellSize.height;
  39507. }
  39508. else if (cellSize !== undefined) {
  39509. this.cellWidth = cellSize;
  39510. this.cellHeight = cellSize;
  39511. }
  39512. else {
  39513. return;
  39514. }
  39515. this._epsilon = epsilon;
  39516. this._scene = scene;
  39517. this._scene.spriteManagers.push(this);
  39518. var indices = [];
  39519. var index = 0;
  39520. for (var count = 0; count < capacity; count++) {
  39521. indices.push(index);
  39522. indices.push(index + 1);
  39523. indices.push(index + 2);
  39524. indices.push(index);
  39525. indices.push(index + 2);
  39526. indices.push(index + 3);
  39527. index += 4;
  39528. }
  39529. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39530. // VBO
  39531. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  39532. this._vertexData = new Float32Array(capacity * 16 * 4);
  39533. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  39534. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  39535. var options = this._buffer.createVertexBuffer("options", 4, 4);
  39536. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  39537. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  39538. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39539. this._vertexBuffers["options"] = options;
  39540. this._vertexBuffers["cellInfo"] = cellInfo;
  39541. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39542. // Effects
  39543. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  39544. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  39545. }
  39546. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  39547. set: function (callback) {
  39548. if (this._onDisposeObserver) {
  39549. this.onDisposeObservable.remove(this._onDisposeObserver);
  39550. }
  39551. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39552. },
  39553. enumerable: true,
  39554. configurable: true
  39555. });
  39556. Object.defineProperty(SpriteManager.prototype, "texture", {
  39557. get: function () {
  39558. return this._spriteTexture;
  39559. },
  39560. set: function (value) {
  39561. this._spriteTexture = value;
  39562. },
  39563. enumerable: true,
  39564. configurable: true
  39565. });
  39566. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  39567. var arrayOffset = index * 16;
  39568. if (offsetX === 0)
  39569. offsetX = this._epsilon;
  39570. else if (offsetX === 1)
  39571. offsetX = 1 - this._epsilon;
  39572. if (offsetY === 0)
  39573. offsetY = this._epsilon;
  39574. else if (offsetY === 1)
  39575. offsetY = 1 - this._epsilon;
  39576. this._vertexData[arrayOffset] = sprite.position.x;
  39577. this._vertexData[arrayOffset + 1] = sprite.position.y;
  39578. this._vertexData[arrayOffset + 2] = sprite.position.z;
  39579. this._vertexData[arrayOffset + 3] = sprite.angle;
  39580. this._vertexData[arrayOffset + 4] = sprite.width;
  39581. this._vertexData[arrayOffset + 5] = sprite.height;
  39582. this._vertexData[arrayOffset + 6] = offsetX;
  39583. this._vertexData[arrayOffset + 7] = offsetY;
  39584. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  39585. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  39586. var offset = (sprite.cellIndex / rowSize) >> 0;
  39587. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  39588. this._vertexData[arrayOffset + 11] = offset;
  39589. // Color
  39590. this._vertexData[arrayOffset + 12] = sprite.color.r;
  39591. this._vertexData[arrayOffset + 13] = sprite.color.g;
  39592. this._vertexData[arrayOffset + 14] = sprite.color.b;
  39593. this._vertexData[arrayOffset + 15] = sprite.color.a;
  39594. };
  39595. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  39596. var count = Math.min(this._capacity, this.sprites.length);
  39597. var min = BABYLON.Vector3.Zero();
  39598. var max = BABYLON.Vector3.Zero();
  39599. var distance = Number.MAX_VALUE;
  39600. var currentSprite;
  39601. var cameraSpacePosition = BABYLON.Vector3.Zero();
  39602. var cameraView = camera.getViewMatrix();
  39603. for (var index = 0; index < count; index++) {
  39604. var sprite = this.sprites[index];
  39605. if (!sprite) {
  39606. continue;
  39607. }
  39608. if (predicate) {
  39609. if (!predicate(sprite)) {
  39610. continue;
  39611. }
  39612. }
  39613. else if (!sprite.isPickable) {
  39614. continue;
  39615. }
  39616. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  39617. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  39618. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  39619. if (ray.intersectsBoxMinMax(min, max)) {
  39620. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  39621. if (distance > currentDistance) {
  39622. distance = currentDistance;
  39623. currentSprite = sprite;
  39624. if (fastCheck) {
  39625. break;
  39626. }
  39627. }
  39628. }
  39629. }
  39630. if (currentSprite) {
  39631. var result = new BABYLON.PickingInfo();
  39632. result.hit = true;
  39633. result.pickedSprite = currentSprite;
  39634. result.distance = distance;
  39635. return result;
  39636. }
  39637. return null;
  39638. };
  39639. SpriteManager.prototype.render = function () {
  39640. // Check
  39641. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  39642. return;
  39643. var engine = this._scene.getEngine();
  39644. var baseSize = this._spriteTexture.getBaseSize();
  39645. // Sprites
  39646. var deltaTime = engine.getDeltaTime();
  39647. var max = Math.min(this._capacity, this.sprites.length);
  39648. var rowSize = baseSize.width / this.cellWidth;
  39649. var offset = 0;
  39650. for (var index = 0; index < max; index++) {
  39651. var sprite = this.sprites[index];
  39652. if (!sprite) {
  39653. continue;
  39654. }
  39655. sprite._animate(deltaTime);
  39656. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  39657. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  39658. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  39659. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  39660. }
  39661. this._buffer.update(this._vertexData);
  39662. // Render
  39663. var effect = this._effectBase;
  39664. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39665. effect = this._effectFog;
  39666. }
  39667. engine.enableEffect(effect);
  39668. var viewMatrix = this._scene.getViewMatrix();
  39669. effect.setTexture("diffuseSampler", this._spriteTexture);
  39670. effect.setMatrix("view", viewMatrix);
  39671. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39672. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  39673. // Fog
  39674. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39675. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  39676. effect.setColor3("vFogColor", this._scene.fogColor);
  39677. }
  39678. // VBOs
  39679. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39680. // Draw order
  39681. engine.setDepthFunctionToLessOrEqual();
  39682. effect.setBool("alphaTest", true);
  39683. engine.setColorWrite(false);
  39684. engine.draw(true, 0, max * 6);
  39685. engine.setColorWrite(true);
  39686. effect.setBool("alphaTest", false);
  39687. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39688. engine.draw(true, 0, max * 6);
  39689. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39690. };
  39691. SpriteManager.prototype.dispose = function () {
  39692. if (this._buffer) {
  39693. this._buffer.dispose();
  39694. this._buffer = null;
  39695. }
  39696. if (this._indexBuffer) {
  39697. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39698. this._indexBuffer = null;
  39699. }
  39700. if (this._spriteTexture) {
  39701. this._spriteTexture.dispose();
  39702. this._spriteTexture = null;
  39703. }
  39704. // Remove from scene
  39705. var index = this._scene.spriteManagers.indexOf(this);
  39706. this._scene.spriteManagers.splice(index, 1);
  39707. // Callback
  39708. this.onDisposeObservable.notifyObservers(this);
  39709. this.onDisposeObservable.clear();
  39710. };
  39711. return SpriteManager;
  39712. }());
  39713. BABYLON.SpriteManager = SpriteManager;
  39714. })(BABYLON || (BABYLON = {}));
  39715. //# sourceMappingURL=babylon.spriteManager.js.map
  39716. var BABYLON;
  39717. (function (BABYLON) {
  39718. var Sprite = (function () {
  39719. function Sprite(name, manager) {
  39720. this.name = name;
  39721. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39722. this.width = 1.0;
  39723. this.height = 1.0;
  39724. this.angle = 0;
  39725. this.cellIndex = 0;
  39726. this.invertU = 0;
  39727. this.invertV = 0;
  39728. this.animations = new Array();
  39729. this.isPickable = false;
  39730. this._animationStarted = false;
  39731. this._loopAnimation = false;
  39732. this._fromIndex = 0;
  39733. this._toIndex = 0;
  39734. this._delay = 0;
  39735. this._direction = 1;
  39736. this._frameCount = 0;
  39737. this._time = 0;
  39738. this._manager = manager;
  39739. this._manager.sprites.push(this);
  39740. this.position = BABYLON.Vector3.Zero();
  39741. }
  39742. Object.defineProperty(Sprite.prototype, "size", {
  39743. get: function () {
  39744. return this.width;
  39745. },
  39746. set: function (value) {
  39747. this.width = value;
  39748. this.height = value;
  39749. },
  39750. enumerable: true,
  39751. configurable: true
  39752. });
  39753. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  39754. this._fromIndex = from;
  39755. this._toIndex = to;
  39756. this._loopAnimation = loop;
  39757. this._delay = delay;
  39758. this._animationStarted = true;
  39759. this._direction = from < to ? 1 : -1;
  39760. this.cellIndex = from;
  39761. this._time = 0;
  39762. this._onAnimationEnd = onAnimationEnd;
  39763. };
  39764. Sprite.prototype.stopAnimation = function () {
  39765. this._animationStarted = false;
  39766. };
  39767. Sprite.prototype._animate = function (deltaTime) {
  39768. if (!this._animationStarted)
  39769. return;
  39770. this._time += deltaTime;
  39771. if (this._time > this._delay) {
  39772. this._time = this._time % this._delay;
  39773. this.cellIndex += this._direction;
  39774. if (this.cellIndex > this._toIndex) {
  39775. if (this._loopAnimation) {
  39776. this.cellIndex = this._fromIndex;
  39777. }
  39778. else {
  39779. this.cellIndex = this._toIndex;
  39780. this._animationStarted = false;
  39781. if (this._onAnimationEnd) {
  39782. this._onAnimationEnd();
  39783. }
  39784. if (this.disposeWhenFinishedAnimating) {
  39785. this.dispose();
  39786. }
  39787. }
  39788. }
  39789. }
  39790. };
  39791. Sprite.prototype.dispose = function () {
  39792. for (var i = 0; i < this._manager.sprites.length; i++) {
  39793. if (this._manager.sprites[i] == this) {
  39794. this._manager.sprites.splice(i, 1);
  39795. }
  39796. }
  39797. };
  39798. return Sprite;
  39799. }());
  39800. BABYLON.Sprite = Sprite;
  39801. })(BABYLON || (BABYLON = {}));
  39802. //# sourceMappingURL=babylon.sprite.js.map
  39803. var BABYLON;
  39804. (function (BABYLON) {
  39805. var IntersectionInfo = (function () {
  39806. function IntersectionInfo(bu, bv, distance) {
  39807. this.bu = bu;
  39808. this.bv = bv;
  39809. this.distance = distance;
  39810. this.faceId = 0;
  39811. this.subMeshId = 0;
  39812. }
  39813. return IntersectionInfo;
  39814. }());
  39815. BABYLON.IntersectionInfo = IntersectionInfo;
  39816. var PickingInfo = (function () {
  39817. function PickingInfo() {
  39818. this.hit = false;
  39819. this.distance = 0;
  39820. this.pickedPoint = null;
  39821. this.pickedMesh = null;
  39822. this.bu = 0;
  39823. this.bv = 0;
  39824. this.faceId = -1;
  39825. this.subMeshId = 0;
  39826. this.pickedSprite = null;
  39827. }
  39828. // Methods
  39829. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  39830. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  39831. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  39832. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39833. return null;
  39834. }
  39835. var indices = this.pickedMesh.getIndices();
  39836. var result;
  39837. if (useVerticesNormals) {
  39838. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39839. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  39840. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  39841. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  39842. normal0 = normal0.scale(this.bu);
  39843. normal1 = normal1.scale(this.bv);
  39844. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  39845. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  39846. }
  39847. else {
  39848. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39849. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  39850. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  39851. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  39852. var p1p2 = vertex1.subtract(vertex2);
  39853. var p3p2 = vertex3.subtract(vertex2);
  39854. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  39855. }
  39856. if (useWorldCoordinates) {
  39857. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  39858. }
  39859. return BABYLON.Vector3.Normalize(result);
  39860. };
  39861. PickingInfo.prototype.getTextureCoordinates = function () {
  39862. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39863. return null;
  39864. }
  39865. var indices = this.pickedMesh.getIndices();
  39866. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39867. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  39868. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  39869. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  39870. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  39871. uv1 = uv1.scale(this.bu);
  39872. uv2 = uv2.scale(this.bv);
  39873. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  39874. };
  39875. return PickingInfo;
  39876. }());
  39877. BABYLON.PickingInfo = PickingInfo;
  39878. })(BABYLON || (BABYLON = {}));
  39879. //# sourceMappingURL=babylon.pickingInfo.js.map
  39880. var BABYLON;
  39881. (function (BABYLON) {
  39882. var Ray = (function () {
  39883. function Ray(origin, direction, length) {
  39884. if (length === void 0) { length = Number.MAX_VALUE; }
  39885. this.origin = origin;
  39886. this.direction = direction;
  39887. this.length = length;
  39888. }
  39889. // Methods
  39890. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  39891. var d = 0.0;
  39892. var maxValue = Number.MAX_VALUE;
  39893. var inv;
  39894. var min;
  39895. var max;
  39896. var temp;
  39897. if (Math.abs(this.direction.x) < 0.0000001) {
  39898. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  39899. return false;
  39900. }
  39901. }
  39902. else {
  39903. inv = 1.0 / this.direction.x;
  39904. min = (minimum.x - this.origin.x) * inv;
  39905. max = (maximum.x - this.origin.x) * inv;
  39906. if (max === -Infinity) {
  39907. max = Infinity;
  39908. }
  39909. if (min > max) {
  39910. temp = min;
  39911. min = max;
  39912. max = temp;
  39913. }
  39914. d = Math.max(min, d);
  39915. maxValue = Math.min(max, maxValue);
  39916. if (d > maxValue) {
  39917. return false;
  39918. }
  39919. }
  39920. if (Math.abs(this.direction.y) < 0.0000001) {
  39921. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  39922. return false;
  39923. }
  39924. }
  39925. else {
  39926. inv = 1.0 / this.direction.y;
  39927. min = (minimum.y - this.origin.y) * inv;
  39928. max = (maximum.y - this.origin.y) * inv;
  39929. if (max === -Infinity) {
  39930. max = Infinity;
  39931. }
  39932. if (min > max) {
  39933. temp = min;
  39934. min = max;
  39935. max = temp;
  39936. }
  39937. d = Math.max(min, d);
  39938. maxValue = Math.min(max, maxValue);
  39939. if (d > maxValue) {
  39940. return false;
  39941. }
  39942. }
  39943. if (Math.abs(this.direction.z) < 0.0000001) {
  39944. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  39945. return false;
  39946. }
  39947. }
  39948. else {
  39949. inv = 1.0 / this.direction.z;
  39950. min = (minimum.z - this.origin.z) * inv;
  39951. max = (maximum.z - this.origin.z) * inv;
  39952. if (max === -Infinity) {
  39953. max = Infinity;
  39954. }
  39955. if (min > max) {
  39956. temp = min;
  39957. min = max;
  39958. max = temp;
  39959. }
  39960. d = Math.max(min, d);
  39961. maxValue = Math.min(max, maxValue);
  39962. if (d > maxValue) {
  39963. return false;
  39964. }
  39965. }
  39966. return true;
  39967. };
  39968. Ray.prototype.intersectsBox = function (box) {
  39969. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  39970. };
  39971. Ray.prototype.intersectsSphere = function (sphere) {
  39972. var x = sphere.center.x - this.origin.x;
  39973. var y = sphere.center.y - this.origin.y;
  39974. var z = sphere.center.z - this.origin.z;
  39975. var pyth = (x * x) + (y * y) + (z * z);
  39976. var rr = sphere.radius * sphere.radius;
  39977. if (pyth <= rr) {
  39978. return true;
  39979. }
  39980. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  39981. if (dot < 0.0) {
  39982. return false;
  39983. }
  39984. var temp = pyth - (dot * dot);
  39985. return temp <= rr;
  39986. };
  39987. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  39988. if (!this._edge1) {
  39989. this._edge1 = BABYLON.Vector3.Zero();
  39990. this._edge2 = BABYLON.Vector3.Zero();
  39991. this._pvec = BABYLON.Vector3.Zero();
  39992. this._tvec = BABYLON.Vector3.Zero();
  39993. this._qvec = BABYLON.Vector3.Zero();
  39994. }
  39995. vertex1.subtractToRef(vertex0, this._edge1);
  39996. vertex2.subtractToRef(vertex0, this._edge2);
  39997. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  39998. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  39999. if (det === 0) {
  40000. return null;
  40001. }
  40002. var invdet = 1 / det;
  40003. this.origin.subtractToRef(vertex0, this._tvec);
  40004. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  40005. if (bu < 0 || bu > 1.0) {
  40006. return null;
  40007. }
  40008. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  40009. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  40010. if (bv < 0 || bu + bv > 1.0) {
  40011. return null;
  40012. }
  40013. //check if the distance is longer than the predefined length.
  40014. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  40015. if (distance > this.length) {
  40016. return null;
  40017. }
  40018. return new BABYLON.IntersectionInfo(bu, bv, distance);
  40019. };
  40020. Ray.prototype.intersectsPlane = function (plane) {
  40021. var distance;
  40022. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  40023. if (Math.abs(result1) < 9.99999997475243E-07) {
  40024. return null;
  40025. }
  40026. else {
  40027. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  40028. distance = (-plane.d - result2) / result1;
  40029. if (distance < 0.0) {
  40030. if (distance < -9.99999997475243E-07) {
  40031. return null;
  40032. }
  40033. else {
  40034. return 0;
  40035. }
  40036. }
  40037. return distance;
  40038. }
  40039. };
  40040. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  40041. var tm = BABYLON.Tmp.Matrix[0];
  40042. mesh.getWorldMatrix().invertToRef(tm);
  40043. if (this._tmpRay) {
  40044. Ray.TransformToRef(this, tm, this._tmpRay);
  40045. }
  40046. else {
  40047. this._tmpRay = Ray.Transform(this, tm);
  40048. }
  40049. return mesh.intersects(this._tmpRay, fastCheck);
  40050. };
  40051. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  40052. if (results) {
  40053. results.length = 0;
  40054. }
  40055. else {
  40056. results = [];
  40057. }
  40058. for (var i = 0; i < meshes.length; i++) {
  40059. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  40060. if (pickInfo.hit) {
  40061. results.push(pickInfo);
  40062. }
  40063. }
  40064. results.sort(this._comparePickingInfo);
  40065. return results;
  40066. };
  40067. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  40068. if (pickingInfoA.distance < pickingInfoB.distance) {
  40069. return -1;
  40070. }
  40071. else if (pickingInfoA.distance > pickingInfoB.distance) {
  40072. return 1;
  40073. }
  40074. else {
  40075. return 0;
  40076. }
  40077. };
  40078. /**
  40079. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  40080. * @param sega the first point of the segment to test the intersection against
  40081. * @param segb the second point of the segment to test the intersection against
  40082. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  40083. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  40084. */
  40085. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  40086. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  40087. var u = segb.subtract(sega);
  40088. var v = rsegb.subtract(this.origin);
  40089. var w = sega.subtract(this.origin);
  40090. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  40091. var b = BABYLON.Vector3.Dot(u, v);
  40092. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  40093. var d = BABYLON.Vector3.Dot(u, w);
  40094. var e = BABYLON.Vector3.Dot(v, w);
  40095. var D = a * c - b * b; // always >= 0
  40096. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  40097. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  40098. // compute the line parameters of the two closest points
  40099. if (D < Ray.smallnum) {
  40100. sN = 0.0; // force using point P0 on segment S1
  40101. sD = 1.0; // to prevent possible division by 0.0 later
  40102. tN = e;
  40103. tD = c;
  40104. }
  40105. else {
  40106. sN = (b * e - c * d);
  40107. tN = (a * e - b * d);
  40108. if (sN < 0.0) {
  40109. sN = 0.0;
  40110. tN = e;
  40111. tD = c;
  40112. }
  40113. else if (sN > sD) {
  40114. sN = sD;
  40115. tN = e + b;
  40116. tD = c;
  40117. }
  40118. }
  40119. if (tN < 0.0) {
  40120. tN = 0.0;
  40121. // recompute sc for this edge
  40122. if (-d < 0.0) {
  40123. sN = 0.0;
  40124. }
  40125. else if (-d > a)
  40126. sN = sD;
  40127. else {
  40128. sN = -d;
  40129. sD = a;
  40130. }
  40131. }
  40132. else if (tN > tD) {
  40133. tN = tD;
  40134. // recompute sc for this edge
  40135. if ((-d + b) < 0.0) {
  40136. sN = 0;
  40137. }
  40138. else if ((-d + b) > a) {
  40139. sN = sD;
  40140. }
  40141. else {
  40142. sN = (-d + b);
  40143. sD = a;
  40144. }
  40145. }
  40146. // finally do the division to get sc and tc
  40147. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  40148. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  40149. // get the difference of the two closest points
  40150. var qtc = v.multiplyByFloats(tc, tc, tc);
  40151. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  40152. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  40153. if (isIntersected) {
  40154. return qtc.length();
  40155. }
  40156. return -1;
  40157. };
  40158. // Statics
  40159. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  40160. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  40161. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  40162. var direction = end.subtract(start);
  40163. direction.normalize();
  40164. return new Ray(start, direction);
  40165. };
  40166. /**
  40167. * 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
  40168. * transformed to the given world matrix.
  40169. * @param origin The origin point
  40170. * @param end The end point
  40171. * @param world a matrix to transform the ray to. Default is the identity matrix.
  40172. */
  40173. Ray.CreateNewFromTo = function (origin, end, world) {
  40174. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  40175. var direction = end.subtract(origin);
  40176. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  40177. direction.normalize();
  40178. return Ray.Transform(new Ray(origin, direction, length), world);
  40179. };
  40180. Ray.Transform = function (ray, matrix) {
  40181. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  40182. Ray.TransformToRef(ray, matrix, result);
  40183. return result;
  40184. };
  40185. Ray.TransformToRef = function (ray, matrix, result) {
  40186. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  40187. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  40188. result.length = ray.length;
  40189. var dir = result.direction;
  40190. var len = dir.length();
  40191. if (!(len === 0 || len === 1)) {
  40192. var num = 1.0 / len;
  40193. dir.x *= num;
  40194. dir.y *= num;
  40195. dir.z *= num;
  40196. result.length *= len;
  40197. }
  40198. };
  40199. Ray.smallnum = 0.00000001;
  40200. Ray.rayl = 10e8;
  40201. return Ray;
  40202. }());
  40203. BABYLON.Ray = Ray;
  40204. })(BABYLON || (BABYLON = {}));
  40205. //# sourceMappingURL=babylon.ray.js.map
  40206. var BABYLON;
  40207. (function (BABYLON) {
  40208. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  40209. if (boxMin.x > sphereCenter.x + sphereRadius)
  40210. return false;
  40211. if (sphereCenter.x - sphereRadius > boxMax.x)
  40212. return false;
  40213. if (boxMin.y > sphereCenter.y + sphereRadius)
  40214. return false;
  40215. if (sphereCenter.y - sphereRadius > boxMax.y)
  40216. return false;
  40217. if (boxMin.z > sphereCenter.z + sphereRadius)
  40218. return false;
  40219. if (sphereCenter.z - sphereRadius > boxMax.z)
  40220. return false;
  40221. return true;
  40222. };
  40223. var getLowestRoot = (function () {
  40224. var result = { root: 0, found: false };
  40225. return function (a, b, c, maxR) {
  40226. result.root = 0;
  40227. result.found = false;
  40228. var determinant = b * b - 4.0 * a * c;
  40229. if (determinant < 0)
  40230. return result;
  40231. var sqrtD = Math.sqrt(determinant);
  40232. var r1 = (-b - sqrtD) / (2.0 * a);
  40233. var r2 = (-b + sqrtD) / (2.0 * a);
  40234. if (r1 > r2) {
  40235. var temp = r2;
  40236. r2 = r1;
  40237. r1 = temp;
  40238. }
  40239. if (r1 > 0 && r1 < maxR) {
  40240. result.root = r1;
  40241. result.found = true;
  40242. return result;
  40243. }
  40244. if (r2 > 0 && r2 < maxR) {
  40245. result.root = r2;
  40246. result.found = true;
  40247. return result;
  40248. }
  40249. return result;
  40250. };
  40251. })();
  40252. var Collider = (function () {
  40253. function Collider() {
  40254. this.radius = BABYLON.Vector3.One();
  40255. this.retry = 0;
  40256. this.basePointWorld = BABYLON.Vector3.Zero();
  40257. this.velocityWorld = BABYLON.Vector3.Zero();
  40258. this.normalizedVelocity = BABYLON.Vector3.Zero();
  40259. this._collisionPoint = BABYLON.Vector3.Zero();
  40260. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  40261. this._tempVector = BABYLON.Vector3.Zero();
  40262. this._tempVector2 = BABYLON.Vector3.Zero();
  40263. this._tempVector3 = BABYLON.Vector3.Zero();
  40264. this._tempVector4 = BABYLON.Vector3.Zero();
  40265. this._edge = BABYLON.Vector3.Zero();
  40266. this._baseToVertex = BABYLON.Vector3.Zero();
  40267. this._destinationPoint = BABYLON.Vector3.Zero();
  40268. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  40269. this._displacementVector = BABYLON.Vector3.Zero();
  40270. this._collisionMask = -1;
  40271. }
  40272. Object.defineProperty(Collider.prototype, "collisionMask", {
  40273. get: function () {
  40274. return this._collisionMask;
  40275. },
  40276. set: function (mask) {
  40277. this._collisionMask = !isNaN(mask) ? mask : -1;
  40278. },
  40279. enumerable: true,
  40280. configurable: true
  40281. });
  40282. // Methods
  40283. Collider.prototype._initialize = function (source, dir, e) {
  40284. this.velocity = dir;
  40285. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  40286. this.basePoint = source;
  40287. source.multiplyToRef(this.radius, this.basePointWorld);
  40288. dir.multiplyToRef(this.radius, this.velocityWorld);
  40289. this.velocityWorldLength = this.velocityWorld.length();
  40290. this.epsilon = e;
  40291. this.collisionFound = false;
  40292. };
  40293. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  40294. pa.subtractToRef(point, this._tempVector);
  40295. pb.subtractToRef(point, this._tempVector2);
  40296. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  40297. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40298. if (d < 0)
  40299. return false;
  40300. pc.subtractToRef(point, this._tempVector3);
  40301. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  40302. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40303. if (d < 0)
  40304. return false;
  40305. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  40306. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40307. return d >= 0;
  40308. };
  40309. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  40310. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  40311. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  40312. if (distance > this.velocityWorldLength + max + sphereRadius) {
  40313. return false;
  40314. }
  40315. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  40316. return false;
  40317. return true;
  40318. };
  40319. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  40320. var t0;
  40321. var embeddedInPlane = false;
  40322. //defensive programming, actually not needed.
  40323. if (!trianglePlaneArray) {
  40324. trianglePlaneArray = [];
  40325. }
  40326. if (!trianglePlaneArray[faceIndex]) {
  40327. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  40328. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  40329. }
  40330. var trianglePlane = trianglePlaneArray[faceIndex];
  40331. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  40332. return;
  40333. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  40334. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  40335. if (normalDotVelocity == 0) {
  40336. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  40337. return;
  40338. embeddedInPlane = true;
  40339. t0 = 0;
  40340. }
  40341. else {
  40342. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40343. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40344. if (t0 > t1) {
  40345. var temp = t1;
  40346. t1 = t0;
  40347. t0 = temp;
  40348. }
  40349. if (t0 > 1.0 || t1 < 0.0)
  40350. return;
  40351. if (t0 < 0)
  40352. t0 = 0;
  40353. if (t0 > 1.0)
  40354. t0 = 1.0;
  40355. }
  40356. this._collisionPoint.copyFromFloats(0, 0, 0);
  40357. var found = false;
  40358. var t = 1.0;
  40359. if (!embeddedInPlane) {
  40360. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  40361. this.velocity.scaleToRef(t0, this._tempVector);
  40362. this._planeIntersectionPoint.addInPlace(this._tempVector);
  40363. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  40364. found = true;
  40365. t = t0;
  40366. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  40367. }
  40368. }
  40369. if (!found) {
  40370. var velocitySquaredLength = this.velocity.lengthSquared();
  40371. var a = velocitySquaredLength;
  40372. this.basePoint.subtractToRef(p1, this._tempVector);
  40373. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40374. var c = this._tempVector.lengthSquared() - 1.0;
  40375. var lowestRoot = getLowestRoot(a, b, c, t);
  40376. if (lowestRoot.found) {
  40377. t = lowestRoot.root;
  40378. found = true;
  40379. this._collisionPoint.copyFrom(p1);
  40380. }
  40381. this.basePoint.subtractToRef(p2, this._tempVector);
  40382. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40383. c = this._tempVector.lengthSquared() - 1.0;
  40384. lowestRoot = getLowestRoot(a, b, c, t);
  40385. if (lowestRoot.found) {
  40386. t = lowestRoot.root;
  40387. found = true;
  40388. this._collisionPoint.copyFrom(p2);
  40389. }
  40390. this.basePoint.subtractToRef(p3, this._tempVector);
  40391. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40392. c = this._tempVector.lengthSquared() - 1.0;
  40393. lowestRoot = getLowestRoot(a, b, c, t);
  40394. if (lowestRoot.found) {
  40395. t = lowestRoot.root;
  40396. found = true;
  40397. this._collisionPoint.copyFrom(p3);
  40398. }
  40399. p2.subtractToRef(p1, this._edge);
  40400. p1.subtractToRef(this.basePoint, this._baseToVertex);
  40401. var edgeSquaredLength = this._edge.lengthSquared();
  40402. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40403. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40404. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40405. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40406. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40407. lowestRoot = getLowestRoot(a, b, c, t);
  40408. if (lowestRoot.found) {
  40409. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40410. if (f >= 0.0 && f <= 1.0) {
  40411. t = lowestRoot.root;
  40412. found = true;
  40413. this._edge.scaleInPlace(f);
  40414. p1.addToRef(this._edge, this._collisionPoint);
  40415. }
  40416. }
  40417. p3.subtractToRef(p2, this._edge);
  40418. p2.subtractToRef(this.basePoint, this._baseToVertex);
  40419. edgeSquaredLength = this._edge.lengthSquared();
  40420. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40421. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40422. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40423. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40424. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40425. lowestRoot = getLowestRoot(a, b, c, t);
  40426. if (lowestRoot.found) {
  40427. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40428. if (f >= 0.0 && f <= 1.0) {
  40429. t = lowestRoot.root;
  40430. found = true;
  40431. this._edge.scaleInPlace(f);
  40432. p2.addToRef(this._edge, this._collisionPoint);
  40433. }
  40434. }
  40435. p1.subtractToRef(p3, this._edge);
  40436. p3.subtractToRef(this.basePoint, this._baseToVertex);
  40437. edgeSquaredLength = this._edge.lengthSquared();
  40438. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40439. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40440. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40441. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40442. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40443. lowestRoot = getLowestRoot(a, b, c, t);
  40444. if (lowestRoot.found) {
  40445. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40446. if (f >= 0.0 && f <= 1.0) {
  40447. t = lowestRoot.root;
  40448. found = true;
  40449. this._edge.scaleInPlace(f);
  40450. p3.addToRef(this._edge, this._collisionPoint);
  40451. }
  40452. }
  40453. }
  40454. if (found) {
  40455. var distToCollision = t * this.velocity.length();
  40456. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  40457. if (!this.intersectionPoint) {
  40458. this.intersectionPoint = this._collisionPoint.clone();
  40459. }
  40460. else {
  40461. this.intersectionPoint.copyFrom(this._collisionPoint);
  40462. }
  40463. this.nearestDistance = distToCollision;
  40464. this.collisionFound = true;
  40465. }
  40466. }
  40467. };
  40468. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  40469. for (var i = indexStart; i < indexEnd; i += 3) {
  40470. var p1 = pts[indices[i] - decal];
  40471. var p2 = pts[indices[i + 1] - decal];
  40472. var p3 = pts[indices[i + 2] - decal];
  40473. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  40474. }
  40475. };
  40476. Collider.prototype._getResponse = function (pos, vel) {
  40477. pos.addToRef(vel, this._destinationPoint);
  40478. vel.scaleInPlace((this.nearestDistance / vel.length()));
  40479. this.basePoint.addToRef(vel, pos);
  40480. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  40481. this._slidePlaneNormal.normalize();
  40482. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  40483. pos.addInPlace(this._displacementVector);
  40484. this.intersectionPoint.addInPlace(this._displacementVector);
  40485. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  40486. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  40487. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  40488. };
  40489. return Collider;
  40490. }());
  40491. BABYLON.Collider = Collider;
  40492. })(BABYLON || (BABYLON = {}));
  40493. //# sourceMappingURL=babylon.collider.js.map
  40494. var BABYLON;
  40495. (function (BABYLON) {
  40496. //WebWorker code will be inserted to this variable.
  40497. BABYLON.CollisionWorker = "";
  40498. var WorkerTaskType;
  40499. (function (WorkerTaskType) {
  40500. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  40501. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  40502. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  40503. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  40504. var WorkerReplyType;
  40505. (function (WorkerReplyType) {
  40506. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  40507. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  40508. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  40509. var CollisionCoordinatorWorker = (function () {
  40510. function CollisionCoordinatorWorker() {
  40511. var _this = this;
  40512. this._scaledPosition = BABYLON.Vector3.Zero();
  40513. this._scaledVelocity = BABYLON.Vector3.Zero();
  40514. this.onMeshUpdated = function (mesh) {
  40515. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  40516. };
  40517. this.onGeometryUpdated = function (geometry) {
  40518. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  40519. };
  40520. this._afterRender = function () {
  40521. if (!_this._init)
  40522. return;
  40523. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  40524. return;
  40525. }
  40526. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  40527. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  40528. if (_this._runningUpdated > 4) {
  40529. return;
  40530. }
  40531. ++_this._runningUpdated;
  40532. var payload = {
  40533. updatedMeshes: _this._addUpdateMeshesList,
  40534. updatedGeometries: _this._addUpdateGeometriesList,
  40535. removedGeometries: _this._toRemoveGeometryArray,
  40536. removedMeshes: _this._toRemoveMeshesArray
  40537. };
  40538. var message = {
  40539. payload: payload,
  40540. taskType: WorkerTaskType.UPDATE
  40541. };
  40542. var serializable = [];
  40543. for (var id in payload.updatedGeometries) {
  40544. if (payload.updatedGeometries.hasOwnProperty(id)) {
  40545. //prepare transferables
  40546. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  40547. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  40548. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  40549. }
  40550. }
  40551. _this._worker.postMessage(message, serializable);
  40552. _this._addUpdateMeshesList = {};
  40553. _this._addUpdateGeometriesList = {};
  40554. _this._toRemoveGeometryArray = [];
  40555. _this._toRemoveMeshesArray = [];
  40556. };
  40557. this._onMessageFromWorker = function (e) {
  40558. var returnData = e.data;
  40559. if (returnData.error != WorkerReplyType.SUCCESS) {
  40560. //TODO what errors can be returned from the worker?
  40561. BABYLON.Tools.Warn("error returned from worker!");
  40562. return;
  40563. }
  40564. switch (returnData.taskType) {
  40565. case WorkerTaskType.INIT:
  40566. _this._init = true;
  40567. //Update the worked with ALL of the scene's current state
  40568. _this._scene.meshes.forEach(function (mesh) {
  40569. _this.onMeshAdded(mesh);
  40570. });
  40571. _this._scene.getGeometries().forEach(function (geometry) {
  40572. _this.onGeometryAdded(geometry);
  40573. });
  40574. break;
  40575. case WorkerTaskType.UPDATE:
  40576. _this._runningUpdated--;
  40577. break;
  40578. case WorkerTaskType.COLLIDE:
  40579. _this._runningCollisionTask = false;
  40580. var returnPayload = returnData.payload;
  40581. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  40582. return;
  40583. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  40584. //cleanup
  40585. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  40586. break;
  40587. }
  40588. };
  40589. this._collisionsCallbackArray = [];
  40590. this._init = false;
  40591. this._runningUpdated = 0;
  40592. this._runningCollisionTask = false;
  40593. this._addUpdateMeshesList = {};
  40594. this._addUpdateGeometriesList = {};
  40595. this._toRemoveGeometryArray = [];
  40596. this._toRemoveMeshesArray = [];
  40597. }
  40598. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40599. if (!this._init)
  40600. return;
  40601. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  40602. return;
  40603. position.divideToRef(collider.radius, this._scaledPosition);
  40604. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40605. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  40606. var payload = {
  40607. collider: {
  40608. position: this._scaledPosition.asArray(),
  40609. velocity: this._scaledVelocity.asArray(),
  40610. radius: collider.radius.asArray()
  40611. },
  40612. collisionId: collisionIndex,
  40613. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  40614. maximumRetry: maximumRetry
  40615. };
  40616. var message = {
  40617. payload: payload,
  40618. taskType: WorkerTaskType.COLLIDE
  40619. };
  40620. this._worker.postMessage(message);
  40621. };
  40622. CollisionCoordinatorWorker.prototype.init = function (scene) {
  40623. this._scene = scene;
  40624. this._scene.registerAfterRender(this._afterRender);
  40625. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  40626. this._worker = new Worker(workerUrl);
  40627. this._worker.onmessage = this._onMessageFromWorker;
  40628. var message = {
  40629. payload: {},
  40630. taskType: WorkerTaskType.INIT
  40631. };
  40632. this._worker.postMessage(message);
  40633. };
  40634. CollisionCoordinatorWorker.prototype.destroy = function () {
  40635. this._scene.unregisterAfterRender(this._afterRender);
  40636. this._worker.terminate();
  40637. };
  40638. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  40639. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  40640. this.onMeshUpdated(mesh);
  40641. };
  40642. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  40643. this._toRemoveMeshesArray.push(mesh.uniqueId);
  40644. };
  40645. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  40646. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  40647. geometry.onGeometryUpdated = this.onGeometryUpdated;
  40648. this.onGeometryUpdated(geometry);
  40649. };
  40650. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  40651. this._toRemoveGeometryArray.push(geometry.id);
  40652. };
  40653. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  40654. var submeshes = [];
  40655. if (mesh.subMeshes) {
  40656. submeshes = mesh.subMeshes.map(function (sm, idx) {
  40657. return {
  40658. position: idx,
  40659. verticesStart: sm.verticesStart,
  40660. verticesCount: sm.verticesCount,
  40661. indexStart: sm.indexStart,
  40662. indexCount: sm.indexCount,
  40663. hasMaterial: !!sm.getMaterial(),
  40664. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40665. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  40666. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40667. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  40668. };
  40669. });
  40670. }
  40671. var geometryId = null;
  40672. if (mesh instanceof BABYLON.Mesh) {
  40673. geometryId = mesh.geometry ? mesh.geometry.id : null;
  40674. }
  40675. else if (mesh instanceof BABYLON.InstancedMesh) {
  40676. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  40677. }
  40678. return {
  40679. uniqueId: mesh.uniqueId,
  40680. id: mesh.id,
  40681. name: mesh.name,
  40682. geometryId: geometryId,
  40683. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40684. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  40685. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40686. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  40687. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  40688. subMeshes: submeshes,
  40689. checkCollisions: mesh.checkCollisions
  40690. };
  40691. };
  40692. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  40693. return {
  40694. id: geometry.id,
  40695. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  40696. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  40697. indices: new Uint32Array(geometry.getIndices() || []),
  40698. };
  40699. };
  40700. return CollisionCoordinatorWorker;
  40701. }());
  40702. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  40703. var CollisionCoordinatorLegacy = (function () {
  40704. function CollisionCoordinatorLegacy() {
  40705. this._scaledPosition = BABYLON.Vector3.Zero();
  40706. this._scaledVelocity = BABYLON.Vector3.Zero();
  40707. this._finalPosition = BABYLON.Vector3.Zero();
  40708. }
  40709. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40710. position.divideToRef(collider.radius, this._scaledPosition);
  40711. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40712. collider.collidedMesh = null;
  40713. collider.retry = 0;
  40714. collider.initialVelocity = this._scaledVelocity;
  40715. collider.initialPosition = this._scaledPosition;
  40716. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  40717. this._finalPosition.multiplyInPlace(collider.radius);
  40718. //run the callback
  40719. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  40720. };
  40721. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  40722. this._scene = scene;
  40723. };
  40724. CollisionCoordinatorLegacy.prototype.destroy = function () {
  40725. //Legacy need no destruction method.
  40726. };
  40727. //No update in legacy mode
  40728. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  40729. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  40730. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  40731. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  40732. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  40733. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  40734. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  40735. if (excludedMesh === void 0) { excludedMesh = null; }
  40736. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  40737. if (collider.retry >= maximumRetry) {
  40738. finalPosition.copyFrom(position);
  40739. return;
  40740. }
  40741. // Check if this is a mesh else camera or -1
  40742. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  40743. collider._initialize(position, velocity, closeDistance);
  40744. // Check all meshes
  40745. for (var index = 0; index < this._scene.meshes.length; index++) {
  40746. var mesh = this._scene.meshes[index];
  40747. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  40748. mesh._checkCollision(collider);
  40749. }
  40750. }
  40751. if (!collider.collisionFound) {
  40752. position.addToRef(velocity, finalPosition);
  40753. return;
  40754. }
  40755. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  40756. collider._getResponse(position, velocity);
  40757. }
  40758. if (velocity.length() <= closeDistance) {
  40759. finalPosition.copyFrom(position);
  40760. return;
  40761. }
  40762. collider.retry++;
  40763. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  40764. };
  40765. return CollisionCoordinatorLegacy;
  40766. }());
  40767. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  40768. })(BABYLON || (BABYLON = {}));
  40769. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  40770. var BABYLON;
  40771. (function (BABYLON) {
  40772. var Particle = (function () {
  40773. function Particle(particleSystem) {
  40774. this.particleSystem = particleSystem;
  40775. this.position = BABYLON.Vector3.Zero();
  40776. this.direction = BABYLON.Vector3.Zero();
  40777. this.color = new BABYLON.Color4(0, 0, 0, 0);
  40778. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  40779. this.lifeTime = 1.0;
  40780. this.age = 0;
  40781. this.size = 0;
  40782. this.angle = 0;
  40783. this.angularSpeed = 0;
  40784. this._currentFrameCounter = 0;
  40785. this.cellIndex = 0;
  40786. if (!this.particleSystem.isAnimationSheetEnabled) {
  40787. return;
  40788. }
  40789. this.cellIndex = this.particleSystem.startSpriteCellID;
  40790. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  40791. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  40792. }
  40793. else {
  40794. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  40795. }
  40796. }
  40797. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  40798. // (ageOffset / scaledUpdateSpeed) / available cells
  40799. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  40800. this._currentFrameCounter += scaledUpdateSpeed;
  40801. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  40802. this._currentFrameCounter = 0;
  40803. this.cellIndex++;
  40804. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  40805. this.cellIndex = this.particleSystem.endSpriteCellID;
  40806. }
  40807. }
  40808. };
  40809. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  40810. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  40811. this.cellIndex++;
  40812. this._currentFrameCounter = 0;
  40813. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  40814. if (this.particleSystem.spriteCellLoop) {
  40815. this.cellIndex = this.particleSystem.startSpriteCellID;
  40816. }
  40817. else {
  40818. this.cellIndex = this.particleSystem.endSpriteCellID;
  40819. }
  40820. }
  40821. }
  40822. else {
  40823. this._currentFrameCounter++;
  40824. }
  40825. };
  40826. Particle.prototype.copyTo = function (other) {
  40827. other.position.copyFrom(this.position);
  40828. other.direction.copyFrom(this.direction);
  40829. other.color.copyFrom(this.color);
  40830. other.colorStep.copyFrom(this.colorStep);
  40831. other.lifeTime = this.lifeTime;
  40832. other.age = this.age;
  40833. other.size = this.size;
  40834. other.angle = this.angle;
  40835. other.angularSpeed = this.angularSpeed;
  40836. other.particleSystem = this.particleSystem;
  40837. other.cellIndex = this.cellIndex;
  40838. };
  40839. return Particle;
  40840. }());
  40841. BABYLON.Particle = Particle;
  40842. })(BABYLON || (BABYLON = {}));
  40843. //# sourceMappingURL=babylon.particle.js.map
  40844. var BABYLON;
  40845. (function (BABYLON) {
  40846. var randomNumber = function (min, max) {
  40847. if (min === max) {
  40848. return (min);
  40849. }
  40850. var random = Math.random();
  40851. return ((random * (max - min)) + min);
  40852. };
  40853. var ParticleSystem = (function () {
  40854. // end of sheet animation
  40855. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  40856. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  40857. if (epsilon === void 0) { epsilon = 0.01; }
  40858. var _this = this;
  40859. this.name = name;
  40860. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  40861. // Members
  40862. this.animations = [];
  40863. this.renderingGroupId = 0;
  40864. this.emitter = null;
  40865. this.emitRate = 10;
  40866. this.manualEmitCount = -1;
  40867. this.updateSpeed = 0.01;
  40868. this.targetStopDuration = 0;
  40869. this.disposeOnStop = false;
  40870. this.minEmitPower = 1;
  40871. this.maxEmitPower = 1;
  40872. this.minLifeTime = 1;
  40873. this.maxLifeTime = 1;
  40874. this.minSize = 1;
  40875. this.maxSize = 1;
  40876. this.minAngularSpeed = 0;
  40877. this.maxAngularSpeed = 0;
  40878. this.layerMask = 0x0FFFFFFF;
  40879. this.customShader = null;
  40880. this.preventAutoStart = false;
  40881. /**
  40882. * An event triggered when the system is disposed.
  40883. * @type {BABYLON.Observable}
  40884. */
  40885. this.onDisposeObservable = new BABYLON.Observable();
  40886. this.onAnimationEnd = null;
  40887. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  40888. this.forceDepthWrite = false;
  40889. this.gravity = BABYLON.Vector3.Zero();
  40890. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  40891. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  40892. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  40893. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40894. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40895. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40896. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  40897. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40898. this.particles = new Array();
  40899. this._stockParticles = new Array();
  40900. this._newPartsExcess = 0;
  40901. this._vertexBuffers = {};
  40902. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  40903. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  40904. this._scaledDirection = BABYLON.Vector3.Zero();
  40905. this._scaledGravity = BABYLON.Vector3.Zero();
  40906. this._currentRenderId = -1;
  40907. this._started = false;
  40908. this._stopped = false;
  40909. this._actualFrame = 0;
  40910. // sheet animation
  40911. this.startSpriteCellID = 0;
  40912. this.endSpriteCellID = 0;
  40913. this.spriteCellLoop = true;
  40914. this.spriteCellChangeSpeed = 0;
  40915. this.spriteCellWidth = 0;
  40916. this.spriteCellHeight = 0;
  40917. this._vertexBufferSize = 11;
  40918. this.appendParticleVertexes = null;
  40919. this.id = name;
  40920. this._capacity = capacity;
  40921. this._epsilon = epsilon;
  40922. if (_isAnimationSheetEnabled) {
  40923. this._vertexBufferSize = 12;
  40924. }
  40925. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40926. this._customEffect = customEffect;
  40927. scene.particleSystems.push(this);
  40928. this._createIndexBuffer();
  40929. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  40930. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  40931. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  40932. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  40933. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  40934. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  40935. if (this._isAnimationSheetEnabled) {
  40936. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  40937. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  40938. }
  40939. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  40940. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  40941. this._vertexBuffers["options"] = options;
  40942. // Default behaviors
  40943. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  40944. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  40945. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  40946. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  40947. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  40948. };
  40949. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  40950. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  40951. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  40952. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  40953. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  40954. };
  40955. this.updateFunction = function (particles) {
  40956. for (var index = 0; index < particles.length; index++) {
  40957. var particle = particles[index];
  40958. particle.age += _this._scaledUpdateSpeed;
  40959. if (particle.age >= particle.lifeTime) {
  40960. _this.recycleParticle(particle);
  40961. index--;
  40962. continue;
  40963. }
  40964. else {
  40965. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  40966. particle.color.addInPlace(_this._scaledColorStep);
  40967. if (particle.color.a < 0)
  40968. particle.color.a = 0;
  40969. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  40970. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  40971. particle.position.addInPlace(_this._scaledDirection);
  40972. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  40973. particle.direction.addInPlace(_this._scaledGravity);
  40974. if (_this._isAnimationSheetEnabled) {
  40975. particle.updateCellIndex(_this._scaledUpdateSpeed);
  40976. }
  40977. }
  40978. }
  40979. };
  40980. }
  40981. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  40982. set: function (callback) {
  40983. if (this._onDisposeObserver) {
  40984. this.onDisposeObservable.remove(this._onDisposeObserver);
  40985. }
  40986. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40987. },
  40988. enumerable: true,
  40989. configurable: true
  40990. });
  40991. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  40992. get: function () {
  40993. return this._isAnimationSheetEnabled;
  40994. },
  40995. enumerable: true,
  40996. configurable: true
  40997. });
  40998. ParticleSystem.prototype._createIndexBuffer = function () {
  40999. var indices = [];
  41000. var index = 0;
  41001. for (var count = 0; count < this._capacity; count++) {
  41002. indices.push(index);
  41003. indices.push(index + 1);
  41004. indices.push(index + 2);
  41005. indices.push(index);
  41006. indices.push(index + 2);
  41007. indices.push(index + 3);
  41008. index += 4;
  41009. }
  41010. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  41011. };
  41012. ParticleSystem.prototype.recycleParticle = function (particle) {
  41013. var lastParticle = this.particles.pop();
  41014. if (lastParticle !== particle) {
  41015. lastParticle.copyTo(particle);
  41016. this._stockParticles.push(lastParticle);
  41017. }
  41018. };
  41019. ParticleSystem.prototype.getCapacity = function () {
  41020. return this._capacity;
  41021. };
  41022. ParticleSystem.prototype.isAlive = function () {
  41023. return this._alive;
  41024. };
  41025. ParticleSystem.prototype.isStarted = function () {
  41026. return this._started;
  41027. };
  41028. ParticleSystem.prototype.start = function () {
  41029. this._started = true;
  41030. this._stopped = false;
  41031. this._actualFrame = 0;
  41032. };
  41033. ParticleSystem.prototype.stop = function () {
  41034. this._stopped = true;
  41035. };
  41036. // animation sheet
  41037. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  41038. var offset = index * this._vertexBufferSize;
  41039. this._vertexData[offset] = particle.position.x;
  41040. this._vertexData[offset + 1] = particle.position.y;
  41041. this._vertexData[offset + 2] = particle.position.z;
  41042. this._vertexData[offset + 3] = particle.color.r;
  41043. this._vertexData[offset + 4] = particle.color.g;
  41044. this._vertexData[offset + 5] = particle.color.b;
  41045. this._vertexData[offset + 6] = particle.color.a;
  41046. this._vertexData[offset + 7] = particle.angle;
  41047. this._vertexData[offset + 8] = particle.size;
  41048. this._vertexData[offset + 9] = offsetX;
  41049. this._vertexData[offset + 10] = offsetY;
  41050. };
  41051. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  41052. if (offsetX === 0)
  41053. offsetX = this._epsilon;
  41054. else if (offsetX === 1)
  41055. offsetX = 1 - this._epsilon;
  41056. if (offsetY === 0)
  41057. offsetY = this._epsilon;
  41058. else if (offsetY === 1)
  41059. offsetY = 1 - this._epsilon;
  41060. var offset = index * this._vertexBufferSize;
  41061. this._vertexData[offset] = particle.position.x;
  41062. this._vertexData[offset + 1] = particle.position.y;
  41063. this._vertexData[offset + 2] = particle.position.z;
  41064. this._vertexData[offset + 3] = particle.color.r;
  41065. this._vertexData[offset + 4] = particle.color.g;
  41066. this._vertexData[offset + 5] = particle.color.b;
  41067. this._vertexData[offset + 6] = particle.color.a;
  41068. this._vertexData[offset + 7] = particle.angle;
  41069. this._vertexData[offset + 8] = particle.size;
  41070. this._vertexData[offset + 9] = offsetX;
  41071. this._vertexData[offset + 10] = offsetY;
  41072. this._vertexData[offset + 11] = particle.cellIndex;
  41073. };
  41074. ParticleSystem.prototype._update = function (newParticles) {
  41075. // Update current
  41076. this._alive = this.particles.length > 0;
  41077. this.updateFunction(this.particles);
  41078. // Add new ones
  41079. var worldMatrix;
  41080. if (this.emitter.position) {
  41081. var emitterMesh = this.emitter;
  41082. worldMatrix = emitterMesh.getWorldMatrix();
  41083. }
  41084. else {
  41085. var emitterPosition = this.emitter;
  41086. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  41087. }
  41088. var particle;
  41089. for (var index = 0; index < newParticles; index++) {
  41090. if (this.particles.length === this._capacity) {
  41091. break;
  41092. }
  41093. if (this._stockParticles.length !== 0) {
  41094. particle = this._stockParticles.pop();
  41095. particle.age = 0;
  41096. particle.cellIndex = this.startSpriteCellID;
  41097. }
  41098. else {
  41099. particle = new BABYLON.Particle(this);
  41100. }
  41101. this.particles.push(particle);
  41102. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  41103. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  41104. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  41105. particle.size = randomNumber(this.minSize, this.maxSize);
  41106. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  41107. this.startPositionFunction(worldMatrix, particle.position, particle);
  41108. var step = randomNumber(0, 1.0);
  41109. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  41110. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  41111. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  41112. }
  41113. };
  41114. ParticleSystem.prototype._getEffect = function () {
  41115. if (this._customEffect) {
  41116. return this._customEffect;
  41117. }
  41118. ;
  41119. var defines = [];
  41120. if (this._scene.clipPlane) {
  41121. defines.push("#define CLIPPLANE");
  41122. }
  41123. if (this._isAnimationSheetEnabled) {
  41124. defines.push("#define ANIMATESHEET");
  41125. }
  41126. // Effect
  41127. var join = defines.join("\n");
  41128. if (this._cachedDefines !== join) {
  41129. this._cachedDefines = join;
  41130. var attributesNamesOrOptions;
  41131. var effectCreationOption;
  41132. if (this._isAnimationSheetEnabled) {
  41133. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  41134. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  41135. }
  41136. else {
  41137. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  41138. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  41139. }
  41140. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  41141. }
  41142. return this._effect;
  41143. };
  41144. ParticleSystem.prototype.animate = function () {
  41145. if (!this._started)
  41146. return;
  41147. var effect = this._getEffect();
  41148. // Check
  41149. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  41150. return;
  41151. if (this._currentRenderId === this._scene.getRenderId()) {
  41152. return;
  41153. }
  41154. this._currentRenderId = this._scene.getRenderId();
  41155. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  41156. // determine the number of particles we need to create
  41157. var newParticles;
  41158. if (this.manualEmitCount > -1) {
  41159. newParticles = this.manualEmitCount;
  41160. this._newPartsExcess = 0;
  41161. this.manualEmitCount = 0;
  41162. }
  41163. else {
  41164. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  41165. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  41166. }
  41167. if (this._newPartsExcess > 1.0) {
  41168. newParticles += this._newPartsExcess >> 0;
  41169. this._newPartsExcess -= this._newPartsExcess >> 0;
  41170. }
  41171. this._alive = false;
  41172. if (!this._stopped) {
  41173. this._actualFrame += this._scaledUpdateSpeed;
  41174. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  41175. this.stop();
  41176. }
  41177. else {
  41178. newParticles = 0;
  41179. }
  41180. this._update(newParticles);
  41181. // Stopped?
  41182. if (this._stopped) {
  41183. if (!this._alive) {
  41184. this._started = false;
  41185. if (this.onAnimationEnd) {
  41186. this.onAnimationEnd();
  41187. }
  41188. if (this.disposeOnStop) {
  41189. this._scene._toBeDisposed.push(this);
  41190. }
  41191. }
  41192. }
  41193. // Animation sheet
  41194. if (this._isAnimationSheetEnabled) {
  41195. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  41196. }
  41197. else {
  41198. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  41199. }
  41200. // Update VBO
  41201. var offset = 0;
  41202. for (var index = 0; index < this.particles.length; index++) {
  41203. var particle = this.particles[index];
  41204. this.appendParticleVertexes(offset, particle);
  41205. offset += 4;
  41206. }
  41207. this._vertexBuffer.update(this._vertexData);
  41208. };
  41209. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  41210. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  41211. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  41212. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  41213. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  41214. };
  41215. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  41216. this._appendParticleVertex(offset++, particle, 0, 0);
  41217. this._appendParticleVertex(offset++, particle, 1, 0);
  41218. this._appendParticleVertex(offset++, particle, 1, 1);
  41219. this._appendParticleVertex(offset++, particle, 0, 1);
  41220. };
  41221. ParticleSystem.prototype.rebuild = function () {
  41222. this._createIndexBuffer();
  41223. this._vertexBuffer._rebuild();
  41224. };
  41225. ParticleSystem.prototype.render = function () {
  41226. var effect = this._getEffect();
  41227. // Check
  41228. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  41229. return 0;
  41230. var engine = this._scene.getEngine();
  41231. // Render
  41232. engine.enableEffect(effect);
  41233. engine.setState(false);
  41234. var viewMatrix = this._scene.getViewMatrix();
  41235. effect.setTexture("diffuseSampler", this.particleTexture);
  41236. effect.setMatrix("view", viewMatrix);
  41237. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  41238. if (this._isAnimationSheetEnabled) {
  41239. var baseSize = this.particleTexture.getBaseSize();
  41240. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  41241. }
  41242. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  41243. if (this._scene.clipPlane) {
  41244. var clipPlane = this._scene.clipPlane;
  41245. var invView = viewMatrix.clone();
  41246. invView.invert();
  41247. effect.setMatrix("invView", invView);
  41248. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41249. }
  41250. // VBOs
  41251. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41252. // Draw order
  41253. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  41254. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  41255. }
  41256. else {
  41257. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41258. }
  41259. if (this.forceDepthWrite) {
  41260. engine.setDepthWrite(true);
  41261. }
  41262. engine.draw(true, 0, this.particles.length * 6);
  41263. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41264. return this.particles.length;
  41265. };
  41266. ParticleSystem.prototype.dispose = function () {
  41267. if (this._vertexBuffer) {
  41268. this._vertexBuffer.dispose();
  41269. this._vertexBuffer = null;
  41270. }
  41271. if (this._indexBuffer) {
  41272. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41273. this._indexBuffer = null;
  41274. }
  41275. if (this.particleTexture) {
  41276. this.particleTexture.dispose();
  41277. this.particleTexture = null;
  41278. }
  41279. // Remove from scene
  41280. var index = this._scene.particleSystems.indexOf(this);
  41281. if (index > -1) {
  41282. this._scene.particleSystems.splice(index, 1);
  41283. }
  41284. // Callback
  41285. this.onDisposeObservable.notifyObservers(this);
  41286. this.onDisposeObservable.clear();
  41287. };
  41288. // Clone
  41289. ParticleSystem.prototype.clone = function (name, newEmitter) {
  41290. var custom = null;
  41291. var program = null;
  41292. if (this.customShader != null) {
  41293. program = this.customShader;
  41294. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41295. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41296. }
  41297. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  41298. result.customShader = program;
  41299. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  41300. if (newEmitter === undefined) {
  41301. newEmitter = this.emitter;
  41302. }
  41303. result.emitter = newEmitter;
  41304. if (this.particleTexture) {
  41305. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  41306. }
  41307. if (!this.preventAutoStart) {
  41308. result.start();
  41309. }
  41310. return result;
  41311. };
  41312. ParticleSystem.prototype.serialize = function () {
  41313. var serializationObject = {};
  41314. serializationObject.name = this.name;
  41315. serializationObject.id = this.id;
  41316. // Emitter
  41317. if (this.emitter.position) {
  41318. var emitterMesh = this.emitter;
  41319. serializationObject.emitterId = emitterMesh.id;
  41320. }
  41321. else {
  41322. var emitterPosition = this.emitter;
  41323. serializationObject.emitter = emitterPosition.asArray();
  41324. }
  41325. serializationObject.capacity = this.getCapacity();
  41326. if (this.particleTexture) {
  41327. serializationObject.textureName = this.particleTexture.name;
  41328. }
  41329. // Animations
  41330. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  41331. // Particle system
  41332. serializationObject.minAngularSpeed = this.minAngularSpeed;
  41333. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  41334. serializationObject.minSize = this.minSize;
  41335. serializationObject.maxSize = this.maxSize;
  41336. serializationObject.minEmitPower = this.minEmitPower;
  41337. serializationObject.maxEmitPower = this.maxEmitPower;
  41338. serializationObject.minLifeTime = this.minLifeTime;
  41339. serializationObject.maxLifeTime = this.maxLifeTime;
  41340. serializationObject.emitRate = this.emitRate;
  41341. serializationObject.minEmitBox = this.minEmitBox.asArray();
  41342. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  41343. serializationObject.gravity = this.gravity.asArray();
  41344. serializationObject.direction1 = this.direction1.asArray();
  41345. serializationObject.direction2 = this.direction2.asArray();
  41346. serializationObject.color1 = this.color1.asArray();
  41347. serializationObject.color2 = this.color2.asArray();
  41348. serializationObject.colorDead = this.colorDead.asArray();
  41349. serializationObject.updateSpeed = this.updateSpeed;
  41350. serializationObject.targetStopDuration = this.targetStopDuration;
  41351. serializationObject.textureMask = this.textureMask.asArray();
  41352. serializationObject.blendMode = this.blendMode;
  41353. serializationObject.customShader = this.customShader;
  41354. serializationObject.preventAutoStart = this.preventAutoStart;
  41355. return serializationObject;
  41356. };
  41357. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  41358. var name = parsedParticleSystem.name;
  41359. var custom = null;
  41360. var program = null;
  41361. if (parsedParticleSystem.customShader) {
  41362. program = parsedParticleSystem.customShader;
  41363. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41364. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41365. }
  41366. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  41367. particleSystem.customShader = program;
  41368. if (parsedParticleSystem.id) {
  41369. particleSystem.id = parsedParticleSystem.id;
  41370. }
  41371. // Auto start
  41372. if (parsedParticleSystem.preventAutoStart) {
  41373. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  41374. }
  41375. // Texture
  41376. if (parsedParticleSystem.textureName) {
  41377. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  41378. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  41379. }
  41380. // Emitter
  41381. if (parsedParticleSystem.emitterId) {
  41382. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  41383. }
  41384. else {
  41385. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  41386. }
  41387. // Animations
  41388. if (parsedParticleSystem.animations) {
  41389. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  41390. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  41391. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  41392. }
  41393. }
  41394. if (parsedParticleSystem.autoAnimate) {
  41395. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  41396. }
  41397. // Particle system
  41398. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  41399. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  41400. particleSystem.minSize = parsedParticleSystem.minSize;
  41401. particleSystem.maxSize = parsedParticleSystem.maxSize;
  41402. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  41403. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  41404. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  41405. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  41406. particleSystem.emitRate = parsedParticleSystem.emitRate;
  41407. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  41408. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  41409. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  41410. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  41411. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  41412. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  41413. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  41414. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  41415. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  41416. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  41417. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  41418. particleSystem.blendMode = parsedParticleSystem.blendMode;
  41419. if (!particleSystem.preventAutoStart) {
  41420. particleSystem.start();
  41421. }
  41422. return particleSystem;
  41423. };
  41424. // Statics
  41425. ParticleSystem.BLENDMODE_ONEONE = 0;
  41426. ParticleSystem.BLENDMODE_STANDARD = 1;
  41427. return ParticleSystem;
  41428. }());
  41429. BABYLON.ParticleSystem = ParticleSystem;
  41430. })(BABYLON || (BABYLON = {}));
  41431. //# sourceMappingURL=babylon.particleSystem.js.map
  41432. var BABYLON;
  41433. (function (BABYLON) {
  41434. var SolidParticle = (function () {
  41435. /**
  41436. * Creates a Solid Particle object.
  41437. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  41438. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  41439. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  41440. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  41441. * `shapeId` (integer) is the model shape identifier in the SPS.
  41442. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  41443. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  41444. */
  41445. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  41446. this.idx = 0; // particle global index
  41447. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  41448. this.position = BABYLON.Vector3.Zero(); // position
  41449. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41450. this.scaling = BABYLON.Vector3.One(); // scaling
  41451. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  41452. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41453. this.alive = true; // alive
  41454. this.isVisible = true; // visibility
  41455. this._pos = 0; // index of this particle in the global "positions" array
  41456. this.shapeId = 0; // model shape id
  41457. this.idxInShape = 0; // index of the particle in its shape id
  41458. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  41459. this.idx = particleIndex;
  41460. this._pos = positionIndex;
  41461. this._model = model;
  41462. this.shapeId = shapeId;
  41463. this.idxInShape = idxInShape;
  41464. this._sps = sps;
  41465. if (modelBoundingInfo) {
  41466. this._modelBoundingInfo = modelBoundingInfo;
  41467. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  41468. }
  41469. }
  41470. Object.defineProperty(SolidParticle.prototype, "scale", {
  41471. /**
  41472. * legacy support, changed scale to scaling
  41473. */
  41474. get: function () {
  41475. return this.scaling;
  41476. },
  41477. set: function (scale) {
  41478. this.scaling = scale;
  41479. },
  41480. enumerable: true,
  41481. configurable: true
  41482. });
  41483. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41484. /**
  41485. * legacy support, changed quaternion to rotationQuaternion
  41486. */
  41487. get: function () {
  41488. return this.rotationQuaternion;
  41489. },
  41490. set: function (q) {
  41491. this.rotationQuaternion = q;
  41492. },
  41493. enumerable: true,
  41494. configurable: true
  41495. });
  41496. /**
  41497. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  41498. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  41499. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  41500. */
  41501. SolidParticle.prototype.intersectsMesh = function (target) {
  41502. if (!this._boundingInfo || !target._boundingInfo) {
  41503. return false;
  41504. }
  41505. if (this._sps._bSphereOnly) {
  41506. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  41507. }
  41508. return this._boundingInfo.intersects(target._boundingInfo, false);
  41509. };
  41510. return SolidParticle;
  41511. }());
  41512. BABYLON.SolidParticle = SolidParticle;
  41513. var ModelShape = (function () {
  41514. /**
  41515. * 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.
  41516. * SPS internal tool, don't use it manually.
  41517. */
  41518. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41519. this.shapeID = id;
  41520. this._shape = shape;
  41521. this._shapeUV = shapeUV;
  41522. this._positionFunction = posFunction;
  41523. this._vertexFunction = vtxFunction;
  41524. }
  41525. return ModelShape;
  41526. }());
  41527. BABYLON.ModelShape = ModelShape;
  41528. })(BABYLON || (BABYLON = {}));
  41529. //# sourceMappingURL=babylon.solidParticle.js.map
  41530. var BABYLON;
  41531. (function (BABYLON) {
  41532. /**
  41533. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  41534. */
  41535. var SolidParticleSystem = (function () {
  41536. /**
  41537. * Creates a SPS (Solid Particle System) object.
  41538. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41539. * `scene` (Scene) is the scene in which the SPS is added.
  41540. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  41541. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  41542. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  41543. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  41544. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  41545. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  41546. */
  41547. function SolidParticleSystem(name, scene, options) {
  41548. // public members
  41549. /**
  41550. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41551. * Example : var p = SPS.particles[i];
  41552. */
  41553. this.particles = new Array();
  41554. /**
  41555. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41556. */
  41557. this.nbParticles = 0;
  41558. /**
  41559. * If the particles must ever face the camera (default false). Useful for planar particles.
  41560. */
  41561. this.billboard = false;
  41562. /**
  41563. * Recompute normals when adding a shape
  41564. */
  41565. this.recomputeNormals = true;
  41566. /**
  41567. * This a counter ofr your own usage. It's not set by any SPS functions.
  41568. */
  41569. this.counter = 0;
  41570. /**
  41571. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41572. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  41573. */
  41574. this.vars = {};
  41575. this._positions = new Array();
  41576. this._indices = new Array();
  41577. this._normals = new Array();
  41578. this._colors = new Array();
  41579. this._uvs = new Array();
  41580. this._index = 0; // indices index
  41581. this._updatable = true;
  41582. this._pickable = false;
  41583. this._isVisibilityBoxLocked = false;
  41584. this._alwaysVisible = false;
  41585. this._shapeCounter = 0;
  41586. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  41587. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41588. this._computeParticleColor = true;
  41589. this._computeParticleTexture = true;
  41590. this._computeParticleRotation = true;
  41591. this._computeParticleVertex = false;
  41592. this._computeBoundingBox = false;
  41593. this._cam_axisZ = BABYLON.Vector3.Zero();
  41594. this._cam_axisY = BABYLON.Vector3.Zero();
  41595. this._cam_axisX = BABYLON.Vector3.Zero();
  41596. this._axisX = BABYLON.Axis.X;
  41597. this._axisY = BABYLON.Axis.Y;
  41598. this._axisZ = BABYLON.Axis.Z;
  41599. this._camDir = BABYLON.Vector3.Zero();
  41600. this._rotMatrix = new BABYLON.Matrix();
  41601. this._invertMatrix = new BABYLON.Matrix();
  41602. this._rotated = BABYLON.Vector3.Zero();
  41603. this._quaternion = new BABYLON.Quaternion();
  41604. this._vertex = BABYLON.Vector3.Zero();
  41605. this._normal = BABYLON.Vector3.Zero();
  41606. this._yaw = 0.0;
  41607. this._pitch = 0.0;
  41608. this._roll = 0.0;
  41609. this._halfroll = 0.0;
  41610. this._halfpitch = 0.0;
  41611. this._halfyaw = 0.0;
  41612. this._sinRoll = 0.0;
  41613. this._cosRoll = 0.0;
  41614. this._sinPitch = 0.0;
  41615. this._cosPitch = 0.0;
  41616. this._sinYaw = 0.0;
  41617. this._cosYaw = 0.0;
  41618. this._mustUnrotateFixedNormals = false;
  41619. this._minimum = BABYLON.Tmp.Vector3[0];
  41620. this._maximum = BABYLON.Tmp.Vector3[1];
  41621. this._scale = BABYLON.Tmp.Vector3[2];
  41622. this._translation = BABYLON.Tmp.Vector3[3];
  41623. this._minBbox = BABYLON.Tmp.Vector3[4];
  41624. this._maxBbox = BABYLON.Tmp.Vector3[5];
  41625. this._particlesIntersect = false;
  41626. this._bSphereOnly = false;
  41627. this._bSphereRadiusFactor = 1.0;
  41628. this.name = name;
  41629. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41630. this._camera = scene.activeCamera;
  41631. this._pickable = options ? options.isPickable : false;
  41632. this._particlesIntersect = options ? options.particleIntersection : false;
  41633. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  41634. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  41635. if (options && options.updatable) {
  41636. this._updatable = options.updatable;
  41637. }
  41638. else {
  41639. this._updatable = true;
  41640. }
  41641. if (this._pickable) {
  41642. this.pickedParticles = [];
  41643. }
  41644. }
  41645. /**
  41646. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41647. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41648. */
  41649. SolidParticleSystem.prototype.buildMesh = function () {
  41650. if (this.nbParticles === 0) {
  41651. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41652. this.addShape(triangle, 1);
  41653. triangle.dispose();
  41654. }
  41655. this._positions32 = new Float32Array(this._positions);
  41656. this._uvs32 = new Float32Array(this._uvs);
  41657. this._colors32 = new Float32Array(this._colors);
  41658. if (this.recomputeNormals) {
  41659. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41660. }
  41661. this._normals32 = new Float32Array(this._normals);
  41662. this._fixedNormal32 = new Float32Array(this._normals);
  41663. if (this._mustUnrotateFixedNormals) {
  41664. this._unrotateFixedNormals();
  41665. }
  41666. var vertexData = new BABYLON.VertexData();
  41667. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41668. vertexData.indices = this._indices;
  41669. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41670. if (this._uvs32) {
  41671. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41672. ;
  41673. }
  41674. if (this._colors32) {
  41675. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41676. }
  41677. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41678. vertexData.applyToMesh(mesh, this._updatable);
  41679. this.mesh = mesh;
  41680. this.mesh.isPickable = this._pickable;
  41681. // free memory
  41682. this._positions = null;
  41683. this._normals = null;
  41684. this._uvs = null;
  41685. this._colors = null;
  41686. if (!this._updatable) {
  41687. this.particles.length = 0;
  41688. }
  41689. return mesh;
  41690. };
  41691. /**
  41692. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41693. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41694. * Thus the particles generated from `digest()` have their property `position` set yet.
  41695. * `mesh` ( Mesh ) is the mesh to be digested
  41696. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41697. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41698. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41699. */
  41700. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41701. var size = (options && options.facetNb) || 1;
  41702. var number = (options && options.number);
  41703. var delta = (options && options.delta) || 0;
  41704. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41705. var meshInd = mesh.getIndices();
  41706. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41707. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41708. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41709. var f = 0; // facet counter
  41710. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41711. // compute size from number
  41712. if (number) {
  41713. number = (number > totalFacets) ? totalFacets : number;
  41714. size = Math.round(totalFacets / number);
  41715. delta = 0;
  41716. }
  41717. else {
  41718. size = (size > totalFacets) ? totalFacets : size;
  41719. }
  41720. var facetPos = []; // submesh positions
  41721. var facetInd = []; // submesh indices
  41722. var facetUV = []; // submesh UV
  41723. var facetCol = []; // submesh colors
  41724. var barycenter = BABYLON.Tmp.Vector3[0];
  41725. var rand;
  41726. var sizeO = size;
  41727. while (f < totalFacets) {
  41728. size = sizeO + Math.floor((1 + delta) * Math.random());
  41729. if (f > totalFacets - size) {
  41730. size = totalFacets - f;
  41731. }
  41732. // reset temp arrays
  41733. facetPos.length = 0;
  41734. facetInd.length = 0;
  41735. facetUV.length = 0;
  41736. facetCol.length = 0;
  41737. // iterate over "size" facets
  41738. var fi = 0;
  41739. for (var j = f * 3; j < (f + size) * 3; j++) {
  41740. facetInd.push(fi);
  41741. var i = meshInd[j];
  41742. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41743. if (meshUV) {
  41744. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41745. }
  41746. if (meshCol) {
  41747. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41748. }
  41749. fi++;
  41750. }
  41751. // create a model shape for each single particle
  41752. var idx = this.nbParticles;
  41753. var shape = this._posToShape(facetPos);
  41754. var shapeUV = this._uvsToShapeUV(facetUV);
  41755. // compute the barycenter of the shape
  41756. var v;
  41757. for (v = 0; v < shape.length; v++) {
  41758. barycenter.addInPlace(shape[v]);
  41759. }
  41760. barycenter.scaleInPlace(1 / shape.length);
  41761. // shift the shape from its barycenter to the origin
  41762. for (v = 0; v < shape.length; v++) {
  41763. shape[v].subtractInPlace(barycenter);
  41764. }
  41765. var bInfo;
  41766. if (this._particlesIntersect) {
  41767. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  41768. }
  41769. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41770. // add the particle in the SPS
  41771. var currentPos = this._positions.length;
  41772. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  41773. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  41774. // initialize the particle position
  41775. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41776. this._index += shape.length;
  41777. idx++;
  41778. this.nbParticles++;
  41779. this._shapeCounter++;
  41780. f += size;
  41781. }
  41782. return this;
  41783. };
  41784. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  41785. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  41786. var index = 0;
  41787. var idx = 0;
  41788. for (var p = 0; p < this.particles.length; p++) {
  41789. this._particle = this.particles[p];
  41790. this._shape = this._particle._model._shape;
  41791. if (this._particle.rotationQuaternion) {
  41792. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41793. }
  41794. else {
  41795. this._yaw = this._particle.rotation.y;
  41796. this._pitch = this._particle.rotation.x;
  41797. this._roll = this._particle.rotation.z;
  41798. this._quaternionRotationYPR();
  41799. }
  41800. this._quaternionToRotationMatrix();
  41801. this._rotMatrix.invertToRef(this._invertMatrix);
  41802. for (var pt = 0; pt < this._shape.length; pt++) {
  41803. idx = index + pt * 3;
  41804. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  41805. this._fixedNormal32[idx] = this._normal.x;
  41806. this._fixedNormal32[idx + 1] = this._normal.y;
  41807. this._fixedNormal32[idx + 2] = this._normal.z;
  41808. }
  41809. index = idx + 3;
  41810. }
  41811. };
  41812. //reset copy
  41813. SolidParticleSystem.prototype._resetCopy = function () {
  41814. this._copy.position.x = 0;
  41815. this._copy.position.y = 0;
  41816. this._copy.position.z = 0;
  41817. this._copy.rotation.x = 0;
  41818. this._copy.rotation.y = 0;
  41819. this._copy.rotation.z = 0;
  41820. this._copy.rotationQuaternion = null;
  41821. this._copy.scaling.x = 1;
  41822. this._copy.scaling.y = 1;
  41823. this._copy.scaling.z = 1;
  41824. this._copy.uvs.x = 0;
  41825. this._copy.uvs.y = 0;
  41826. this._copy.uvs.z = 1;
  41827. this._copy.uvs.w = 1;
  41828. this._copy.color = null;
  41829. };
  41830. // _meshBuilder : inserts the shape model in the global SPS mesh
  41831. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  41832. var i;
  41833. var u = 0;
  41834. var c = 0;
  41835. var n = 0;
  41836. this._resetCopy();
  41837. if (options && options.positionFunction) {
  41838. options.positionFunction(this._copy, idx, idxInShape);
  41839. this._mustUnrotateFixedNormals = true;
  41840. }
  41841. if (this._copy.rotationQuaternion) {
  41842. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41843. }
  41844. else {
  41845. this._yaw = this._copy.rotation.y;
  41846. this._pitch = this._copy.rotation.x;
  41847. this._roll = this._copy.rotation.z;
  41848. this._quaternionRotationYPR();
  41849. }
  41850. this._quaternionToRotationMatrix();
  41851. for (i = 0; i < shape.length; i++) {
  41852. this._vertex.x = shape[i].x;
  41853. this._vertex.y = shape[i].y;
  41854. this._vertex.z = shape[i].z;
  41855. if (options && options.vertexFunction) {
  41856. options.vertexFunction(this._copy, this._vertex, i);
  41857. }
  41858. this._vertex.x *= this._copy.scaling.x;
  41859. this._vertex.y *= this._copy.scaling.y;
  41860. this._vertex.z *= this._copy.scaling.z;
  41861. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41862. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41863. if (meshUV) {
  41864. 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);
  41865. u += 2;
  41866. }
  41867. if (this._copy.color) {
  41868. this._color = this._copy.color;
  41869. }
  41870. else if (meshCol && meshCol[c] !== undefined) {
  41871. this._color.r = meshCol[c];
  41872. this._color.g = meshCol[c + 1];
  41873. this._color.b = meshCol[c + 2];
  41874. this._color.a = meshCol[c + 3];
  41875. }
  41876. else {
  41877. this._color.r = 1;
  41878. this._color.g = 1;
  41879. this._color.b = 1;
  41880. this._color.a = 1;
  41881. }
  41882. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41883. c += 4;
  41884. if (!this.recomputeNormals && meshNor) {
  41885. this._normal.x = meshNor[n];
  41886. this._normal.y = meshNor[n + 1];
  41887. this._normal.z = meshNor[n + 2];
  41888. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  41889. normals.push(this._normal.x, this._normal.y, this._normal.z);
  41890. n += 3;
  41891. }
  41892. }
  41893. for (i = 0; i < meshInd.length; i++) {
  41894. indices.push(p + meshInd[i]);
  41895. }
  41896. if (this._pickable) {
  41897. var nbfaces = meshInd.length / 3;
  41898. for (i = 0; i < nbfaces; i++) {
  41899. this.pickedParticles.push({ idx: idx, faceId: i });
  41900. }
  41901. }
  41902. return this._copy;
  41903. };
  41904. // returns a shape array from positions array
  41905. SolidParticleSystem.prototype._posToShape = function (positions) {
  41906. var shape = [];
  41907. for (var i = 0; i < positions.length; i += 3) {
  41908. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41909. }
  41910. return shape;
  41911. };
  41912. // returns a shapeUV array from a Vector4 uvs
  41913. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41914. var shapeUV = [];
  41915. if (uvs) {
  41916. for (var i = 0; i < uvs.length; i++)
  41917. shapeUV.push(uvs[i]);
  41918. }
  41919. return shapeUV;
  41920. };
  41921. // adds a new particle object in the particles array
  41922. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  41923. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  41924. this.particles.push(sp);
  41925. return sp;
  41926. };
  41927. /**
  41928. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41929. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  41930. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  41931. * `nb` (positive integer) the number of particles to be created from this model
  41932. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41933. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41934. */
  41935. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41936. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41937. var meshInd = mesh.getIndices();
  41938. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41939. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41940. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41941. var bbInfo;
  41942. if (this._particlesIntersect) {
  41943. bbInfo = mesh.getBoundingInfo();
  41944. }
  41945. var shape = this._posToShape(meshPos);
  41946. var shapeUV = this._uvsToShapeUV(meshUV);
  41947. var posfunc = options ? options.positionFunction : null;
  41948. var vtxfunc = options ? options.vertexFunction : null;
  41949. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41950. // particles
  41951. var sp;
  41952. var currentCopy;
  41953. var idx = this.nbParticles;
  41954. for (var i = 0; i < nb; i++) {
  41955. var currentPos = this._positions.length;
  41956. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  41957. if (this._updatable) {
  41958. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  41959. sp.position.copyFrom(currentCopy.position);
  41960. sp.rotation.copyFrom(currentCopy.rotation);
  41961. if (currentCopy.rotationQuaternion) {
  41962. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  41963. }
  41964. if (currentCopy.color) {
  41965. sp.color.copyFrom(currentCopy.color);
  41966. }
  41967. sp.scaling.copyFrom(currentCopy.scaling);
  41968. sp.uvs.copyFrom(currentCopy.uvs);
  41969. }
  41970. this._index += shape.length;
  41971. idx++;
  41972. }
  41973. this.nbParticles += nb;
  41974. this._shapeCounter++;
  41975. return this._shapeCounter - 1;
  41976. };
  41977. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41978. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41979. this._resetCopy();
  41980. if (particle._model._positionFunction) {
  41981. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41982. }
  41983. if (this._copy.rotationQuaternion) {
  41984. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41985. }
  41986. else {
  41987. this._yaw = this._copy.rotation.y;
  41988. this._pitch = this._copy.rotation.x;
  41989. this._roll = this._copy.rotation.z;
  41990. this._quaternionRotationYPR();
  41991. }
  41992. this._quaternionToRotationMatrix();
  41993. this._shape = particle._model._shape;
  41994. for (var pt = 0; pt < this._shape.length; pt++) {
  41995. this._vertex.x = this._shape[pt].x;
  41996. this._vertex.y = this._shape[pt].y;
  41997. this._vertex.z = this._shape[pt].z;
  41998. if (particle._model._vertexFunction) {
  41999. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  42000. }
  42001. this._vertex.x *= this._copy.scaling.x;
  42002. this._vertex.y *= this._copy.scaling.y;
  42003. this._vertex.z *= this._copy.scaling.z;
  42004. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42005. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  42006. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  42007. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  42008. }
  42009. particle.position.x = 0.0;
  42010. particle.position.y = 0.0;
  42011. particle.position.z = 0.0;
  42012. particle.rotation.x = 0.0;
  42013. particle.rotation.y = 0.0;
  42014. particle.rotation.z = 0.0;
  42015. particle.rotationQuaternion = null;
  42016. particle.scaling.x = 1.0;
  42017. particle.scaling.y = 1.0;
  42018. particle.scaling.z = 1.0;
  42019. };
  42020. /**
  42021. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  42022. * Returns the SPS.
  42023. */
  42024. SolidParticleSystem.prototype.rebuildMesh = function () {
  42025. for (var p = 0; p < this.particles.length; p++) {
  42026. this._rebuildParticle(this.particles[p]);
  42027. }
  42028. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42029. return this;
  42030. };
  42031. /**
  42032. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  42033. * This method calls `updateParticle()` for each particle of the SPS.
  42034. * For an animated SPS, it is usually called within the render loop.
  42035. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  42036. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  42037. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  42038. * Returns the SPS.
  42039. */
  42040. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  42041. if (start === void 0) { start = 0; }
  42042. if (end === void 0) { end = this.nbParticles - 1; }
  42043. if (update === void 0) { update = true; }
  42044. if (!this._updatable) {
  42045. return;
  42046. }
  42047. // custom beforeUpdate
  42048. this.beforeUpdateParticles(start, end, update);
  42049. this._cam_axisX.x = 1.0;
  42050. this._cam_axisX.y = 0.0;
  42051. this._cam_axisX.z = 0.0;
  42052. this._cam_axisY.x = 0.0;
  42053. this._cam_axisY.y = 1.0;
  42054. this._cam_axisY.z = 0.0;
  42055. this._cam_axisZ.x = 0.0;
  42056. this._cam_axisZ.y = 0.0;
  42057. this._cam_axisZ.z = 1.0;
  42058. // if the particles will always face the camera
  42059. if (this.billboard) {
  42060. this.mesh.computeWorldMatrix(true);
  42061. // compute the camera position and un-rotate it by the current mesh rotation
  42062. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  42063. this._quaternionToRotationMatrix();
  42064. this._rotMatrix.invertToRef(this._invertMatrix);
  42065. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  42066. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  42067. this._cam_axisZ.normalize();
  42068. // same for camera up vector extracted from the cam view matrix
  42069. var view = this._camera.getViewMatrix(true);
  42070. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  42071. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  42072. this._cam_axisY.normalize();
  42073. this._cam_axisX.normalize();
  42074. }
  42075. }
  42076. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  42077. var idx = 0; // current position index in the global array positions32
  42078. var index = 0; // position start index in the global array positions32 of the current particle
  42079. var colidx = 0; // current color index in the global array colors32
  42080. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  42081. var uvidx = 0; // current uv index in the global array uvs32
  42082. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  42083. var pt = 0; // current index in the particle model shape
  42084. if (this.mesh.isFacetDataEnabled) {
  42085. this._computeBoundingBox = true;
  42086. }
  42087. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  42088. if (this._computeBoundingBox) {
  42089. if (start == 0 && end == this.nbParticles - 1) {
  42090. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  42091. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  42092. }
  42093. else {
  42094. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  42095. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  42096. }
  42097. }
  42098. // particle loop
  42099. index = this.particles[start]._pos;
  42100. var vpos = (index / 3) | 0;
  42101. colorIndex = vpos * 4;
  42102. uvIndex = vpos * 2;
  42103. for (var p = start; p <= end; p++) {
  42104. this._particle = this.particles[p];
  42105. this._shape = this._particle._model._shape;
  42106. this._shapeUV = this._particle._model._shapeUV;
  42107. // call to custom user function to update the particle properties
  42108. this.updateParticle(this._particle);
  42109. // skip the computations for inactive or already invisible particles
  42110. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  42111. // increment indexes for the next particle
  42112. pt = this._shape.length;
  42113. index += pt * 3;
  42114. colorIndex += pt * 4;
  42115. uvIndex += pt * 2;
  42116. continue;
  42117. }
  42118. if (this._particle.isVisible) {
  42119. this._particle._stillInvisible = false; // un-mark permanent invisibility
  42120. // particle rotation matrix
  42121. if (this.billboard) {
  42122. this._particle.rotation.x = 0.0;
  42123. this._particle.rotation.y = 0.0;
  42124. }
  42125. if (this._computeParticleRotation || this.billboard) {
  42126. if (this._particle.rotationQuaternion) {
  42127. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  42128. }
  42129. else {
  42130. this._yaw = this._particle.rotation.y;
  42131. this._pitch = this._particle.rotation.x;
  42132. this._roll = this._particle.rotation.z;
  42133. this._quaternionRotationYPR();
  42134. }
  42135. this._quaternionToRotationMatrix();
  42136. }
  42137. // particle vertex loop
  42138. for (pt = 0; pt < this._shape.length; pt++) {
  42139. idx = index + pt * 3;
  42140. colidx = colorIndex + pt * 4;
  42141. uvidx = uvIndex + pt * 2;
  42142. this._vertex.x = this._shape[pt].x;
  42143. this._vertex.y = this._shape[pt].y;
  42144. this._vertex.z = this._shape[pt].z;
  42145. if (this._computeParticleVertex) {
  42146. this.updateParticleVertex(this._particle, this._vertex, pt);
  42147. }
  42148. // positions
  42149. this._vertex.x *= this._particle.scaling.x;
  42150. this._vertex.y *= this._particle.scaling.y;
  42151. this._vertex.z *= this._particle.scaling.z;
  42152. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  42153. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  42154. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  42155. 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;
  42156. 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;
  42157. 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;
  42158. if (this._computeBoundingBox) {
  42159. if (this._positions32[idx] < this._minimum.x) {
  42160. this._minimum.x = this._positions32[idx];
  42161. }
  42162. if (this._positions32[idx] > this._maximum.x) {
  42163. this._maximum.x = this._positions32[idx];
  42164. }
  42165. if (this._positions32[idx + 1] < this._minimum.y) {
  42166. this._minimum.y = this._positions32[idx + 1];
  42167. }
  42168. if (this._positions32[idx + 1] > this._maximum.y) {
  42169. this._maximum.y = this._positions32[idx + 1];
  42170. }
  42171. if (this._positions32[idx + 2] < this._minimum.z) {
  42172. this._minimum.z = this._positions32[idx + 2];
  42173. }
  42174. if (this._positions32[idx + 2] > this._maximum.z) {
  42175. this._maximum.z = this._positions32[idx + 2];
  42176. }
  42177. }
  42178. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  42179. if (!this._computeParticleVertex) {
  42180. this._normal.x = this._fixedNormal32[idx];
  42181. this._normal.y = this._fixedNormal32[idx + 1];
  42182. this._normal.z = this._fixedNormal32[idx + 2];
  42183. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  42184. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  42185. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  42186. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42187. 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;
  42188. 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;
  42189. }
  42190. if (this._computeParticleColor) {
  42191. this._colors32[colidx] = this._particle.color.r;
  42192. this._colors32[colidx + 1] = this._particle.color.g;
  42193. this._colors32[colidx + 2] = this._particle.color.b;
  42194. this._colors32[colidx + 3] = this._particle.color.a;
  42195. }
  42196. if (this._computeParticleTexture) {
  42197. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42198. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42199. }
  42200. }
  42201. }
  42202. else {
  42203. this._particle._stillInvisible = true; // mark the particle as invisible
  42204. for (pt = 0; pt < this._shape.length; pt++) {
  42205. idx = index + pt * 3;
  42206. colidx = colorIndex + pt * 4;
  42207. uvidx = uvIndex + pt * 2;
  42208. this._positions32[idx] = 0.0;
  42209. this._positions32[idx + 1] = 0.0;
  42210. this._positions32[idx + 2] = 0.0;
  42211. this._normals32[idx] = 0.0;
  42212. this._normals32[idx + 1] = 0.0;
  42213. this._normals32[idx + 2] = 0.0;
  42214. if (this._computeParticleColor) {
  42215. this._colors32[colidx] = this._particle.color.r;
  42216. this._colors32[colidx + 1] = this._particle.color.g;
  42217. this._colors32[colidx + 2] = this._particle.color.b;
  42218. this._colors32[colidx + 3] = this._particle.color.a;
  42219. }
  42220. if (this._computeParticleTexture) {
  42221. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42222. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42223. }
  42224. }
  42225. }
  42226. // if the particle intersections must be computed : update the bbInfo
  42227. if (this._particlesIntersect) {
  42228. var bInfo = this._particle._boundingInfo;
  42229. var bBox = bInfo.boundingBox;
  42230. var bSphere = bInfo.boundingSphere;
  42231. if (!this._bSphereOnly) {
  42232. // place, scale and rotate the particle bbox within the SPS local system, then update it
  42233. for (var b = 0; b < bBox.vectors.length; b++) {
  42234. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  42235. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  42236. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  42237. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  42238. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  42239. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  42240. 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;
  42241. 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;
  42242. 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;
  42243. }
  42244. bBox._update(this.mesh._worldMatrix);
  42245. }
  42246. // place and scale the particle bouding sphere in the SPS local system, then update it
  42247. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  42248. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  42249. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  42250. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  42251. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  42252. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  42253. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  42254. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  42255. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  42256. 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));
  42257. bSphere._update(this.mesh._worldMatrix);
  42258. }
  42259. // increment indexes for the next particle
  42260. index = idx + 3;
  42261. colorIndex = colidx + 4;
  42262. uvIndex = uvidx + 2;
  42263. }
  42264. // if the VBO must be updated
  42265. if (update) {
  42266. if (this._computeParticleColor) {
  42267. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  42268. }
  42269. if (this._computeParticleTexture) {
  42270. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  42271. }
  42272. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42273. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  42274. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  42275. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  42276. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  42277. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  42278. for (var i = 0; i < this._normals32.length; i++) {
  42279. this._fixedNormal32[i] = this._normals32[i];
  42280. }
  42281. }
  42282. if (!this.mesh.areNormalsFrozen) {
  42283. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  42284. }
  42285. }
  42286. }
  42287. if (this._computeBoundingBox) {
  42288. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  42289. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  42290. }
  42291. this.afterUpdateParticles(start, end, update);
  42292. return this;
  42293. };
  42294. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42295. this._halfroll = this._roll * 0.5;
  42296. this._halfpitch = this._pitch * 0.5;
  42297. this._halfyaw = this._yaw * 0.5;
  42298. this._sinRoll = Math.sin(this._halfroll);
  42299. this._cosRoll = Math.cos(this._halfroll);
  42300. this._sinPitch = Math.sin(this._halfpitch);
  42301. this._cosPitch = Math.cos(this._halfpitch);
  42302. this._sinYaw = Math.sin(this._halfyaw);
  42303. this._cosYaw = Math.cos(this._halfyaw);
  42304. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  42305. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  42306. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  42307. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  42308. };
  42309. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42310. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42311. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42312. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42313. this._rotMatrix.m[3] = 0;
  42314. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42315. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42316. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42317. this._rotMatrix.m[7] = 0;
  42318. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42319. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42320. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42321. this._rotMatrix.m[11] = 0;
  42322. this._rotMatrix.m[12] = 0;
  42323. this._rotMatrix.m[13] = 0;
  42324. this._rotMatrix.m[14] = 0;
  42325. this._rotMatrix.m[15] = 1.0;
  42326. };
  42327. /**
  42328. * Disposes the SPS.
  42329. * Returns nothing.
  42330. */
  42331. SolidParticleSystem.prototype.dispose = function () {
  42332. this.mesh.dispose();
  42333. this.vars = null;
  42334. // drop references to internal big arrays for the GC
  42335. this._positions = null;
  42336. this._indices = null;
  42337. this._normals = null;
  42338. this._uvs = null;
  42339. this._colors = null;
  42340. this._positions32 = null;
  42341. this._normals32 = null;
  42342. this._fixedNormal32 = null;
  42343. this._uvs32 = null;
  42344. this._colors32 = null;
  42345. this.pickedParticles = null;
  42346. };
  42347. /**
  42348. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42349. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42350. * Returns the SPS.
  42351. */
  42352. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42353. if (!this._isVisibilityBoxLocked) {
  42354. this.mesh.refreshBoundingInfo();
  42355. }
  42356. return this;
  42357. };
  42358. /**
  42359. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42360. * @param size the size (float) of the visibility box
  42361. * note : this doesn't lock the SPS mesh bounding box.
  42362. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42363. */
  42364. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42365. var vis = size / 2;
  42366. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42367. };
  42368. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42369. // getter and setter
  42370. get: function () {
  42371. return this._alwaysVisible;
  42372. },
  42373. /**
  42374. * Sets the SPS as always visible or not
  42375. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42376. */
  42377. set: function (val) {
  42378. this._alwaysVisible = val;
  42379. this.mesh.alwaysSelectAsActiveMesh = val;
  42380. },
  42381. enumerable: true,
  42382. configurable: true
  42383. });
  42384. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42385. get: function () {
  42386. return this._isVisibilityBoxLocked;
  42387. },
  42388. /**
  42389. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42390. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42391. */
  42392. set: function (val) {
  42393. this._isVisibilityBoxLocked = val;
  42394. this.mesh.getBoundingInfo().isLocked = val;
  42395. },
  42396. enumerable: true,
  42397. configurable: true
  42398. });
  42399. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42400. // getters
  42401. get: function () {
  42402. return this._computeParticleRotation;
  42403. },
  42404. // Optimizer setters
  42405. /**
  42406. * Tells to `setParticles()` to compute the particle rotations or not.
  42407. * Default value : true. The SPS is faster when it's set to false.
  42408. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42409. */
  42410. set: function (val) {
  42411. this._computeParticleRotation = val;
  42412. },
  42413. enumerable: true,
  42414. configurable: true
  42415. });
  42416. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42417. get: function () {
  42418. return this._computeParticleColor;
  42419. },
  42420. /**
  42421. * Tells to `setParticles()` to compute the particle colors or not.
  42422. * Default value : true. The SPS is faster when it's set to false.
  42423. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42424. */
  42425. set: function (val) {
  42426. this._computeParticleColor = val;
  42427. },
  42428. enumerable: true,
  42429. configurable: true
  42430. });
  42431. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42432. get: function () {
  42433. return this._computeParticleTexture;
  42434. },
  42435. /**
  42436. * Tells to `setParticles()` to compute the particle textures or not.
  42437. * Default value : true. The SPS is faster when it's set to false.
  42438. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42439. */
  42440. set: function (val) {
  42441. this._computeParticleTexture = val;
  42442. },
  42443. enumerable: true,
  42444. configurable: true
  42445. });
  42446. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42447. get: function () {
  42448. return this._computeParticleVertex;
  42449. },
  42450. /**
  42451. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42452. * Default value : false. The SPS is faster when it's set to false.
  42453. * Note : the particle custom vertex positions aren't stored values.
  42454. */
  42455. set: function (val) {
  42456. this._computeParticleVertex = val;
  42457. },
  42458. enumerable: true,
  42459. configurable: true
  42460. });
  42461. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42462. get: function () {
  42463. return this._computeBoundingBox;
  42464. },
  42465. /**
  42466. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42467. */
  42468. set: function (val) {
  42469. this._computeBoundingBox = val;
  42470. },
  42471. enumerable: true,
  42472. configurable: true
  42473. });
  42474. // =======================================================================
  42475. // Particle behavior logic
  42476. // these following methods may be overwritten by the user to fit his needs
  42477. /**
  42478. * This function does nothing. It may be overwritten to set all the particle first values.
  42479. * The SPS doesn't call this function, you may have to call it by your own.
  42480. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42481. */
  42482. SolidParticleSystem.prototype.initParticles = function () {
  42483. };
  42484. /**
  42485. * This function does nothing. It may be overwritten to recycle a particle.
  42486. * The SPS doesn't call this function, you may have to call it by your own.
  42487. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42488. */
  42489. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42490. return particle;
  42491. };
  42492. /**
  42493. * Updates a particle : this function should be overwritten by the user.
  42494. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42495. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42496. * ex : just set a particle position or velocity and recycle conditions
  42497. */
  42498. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42499. return particle;
  42500. };
  42501. /**
  42502. * Updates a vertex of a particle : it can be overwritten by the user.
  42503. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42504. * @param particle the current particle
  42505. * @param vertex the current index of the current particle
  42506. * @param pt the index of the current vertex in the particle shape
  42507. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  42508. * ex : just set a vertex particle position
  42509. */
  42510. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42511. return vertex;
  42512. };
  42513. /**
  42514. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42515. * This does nothing and may be overwritten by the user.
  42516. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42517. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42518. * @param update the boolean update value actually passed to setParticles()
  42519. */
  42520. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42521. };
  42522. /**
  42523. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42524. * This will be passed three parameters.
  42525. * This does nothing and may be overwritten by the user.
  42526. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42527. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42528. * @param update the boolean update value actually passed to setParticles()
  42529. */
  42530. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42531. };
  42532. return SolidParticleSystem;
  42533. }());
  42534. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42535. })(BABYLON || (BABYLON = {}));
  42536. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  42537. /// <reference path="babylon.mesh.ts" />
  42538. var BABYLON;
  42539. (function (BABYLON) {
  42540. var GroundMesh = (function (_super) {
  42541. __extends(GroundMesh, _super);
  42542. function GroundMesh(name, scene) {
  42543. var _this = _super.call(this, name, scene) || this;
  42544. _this.generateOctree = false;
  42545. _this._worldInverse = new BABYLON.Matrix();
  42546. return _this;
  42547. }
  42548. GroundMesh.prototype.getClassName = function () {
  42549. return "GroundMesh";
  42550. };
  42551. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  42552. get: function () {
  42553. return Math.min(this._subdivisionsX, this._subdivisionsY);
  42554. },
  42555. enumerable: true,
  42556. configurable: true
  42557. });
  42558. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  42559. get: function () {
  42560. return this._subdivisionsX;
  42561. },
  42562. enumerable: true,
  42563. configurable: true
  42564. });
  42565. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  42566. get: function () {
  42567. return this._subdivisionsY;
  42568. },
  42569. enumerable: true,
  42570. configurable: true
  42571. });
  42572. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  42573. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  42574. this._subdivisionsX = chunksCount;
  42575. this._subdivisionsY = chunksCount;
  42576. this.subdivide(chunksCount);
  42577. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  42578. };
  42579. /**
  42580. * Returns a height (y) value in the Worl system :
  42581. * the ground altitude at the coordinates (x, z) expressed in the World system.
  42582. * Returns the ground y position if (x, z) are outside the ground surface.
  42583. */
  42584. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  42585. var world = this.getWorldMatrix();
  42586. var invMat = BABYLON.Tmp.Matrix[5];
  42587. world.invertToRef(invMat);
  42588. var tmpVect = BABYLON.Tmp.Vector3[8];
  42589. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  42590. x = tmpVect.x;
  42591. z = tmpVect.z;
  42592. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42593. return this.position.y;
  42594. }
  42595. if (!this._heightQuads || this._heightQuads.length == 0) {
  42596. this._initHeightQuads();
  42597. this._computeHeightQuads();
  42598. }
  42599. var facet = this._getFacetAt(x, z);
  42600. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  42601. // return y in the World system
  42602. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  42603. return tmpVect.y;
  42604. };
  42605. /**
  42606. * Returns a normalized vector (Vector3) orthogonal to the ground
  42607. * at the ground coordinates (x, z) expressed in the World system.
  42608. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42609. */
  42610. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42611. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42612. this.getNormalAtCoordinatesToRef(x, z, normal);
  42613. return normal;
  42614. };
  42615. /**
  42616. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42617. * at the ground coordinates (x, z) expressed in the World system.
  42618. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42619. * Returns the GroundMesh.
  42620. */
  42621. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42622. var world = this.getWorldMatrix();
  42623. var tmpMat = BABYLON.Tmp.Matrix[5];
  42624. world.invertToRef(tmpMat);
  42625. var tmpVect = BABYLON.Tmp.Vector3[8];
  42626. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42627. x = tmpVect.x;
  42628. z = tmpVect.z;
  42629. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42630. return this;
  42631. }
  42632. if (!this._heightQuads || this._heightQuads.length == 0) {
  42633. this._initHeightQuads();
  42634. this._computeHeightQuads();
  42635. }
  42636. var facet = this._getFacetAt(x, z);
  42637. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42638. return this;
  42639. };
  42640. /**
  42641. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42642. * if the ground has been updated.
  42643. * This can be used in the render loop.
  42644. * Returns the GroundMesh.
  42645. */
  42646. GroundMesh.prototype.updateCoordinateHeights = function () {
  42647. if (!this._heightQuads || this._heightQuads.length == 0) {
  42648. this._initHeightQuads();
  42649. }
  42650. this._computeHeightQuads();
  42651. return this;
  42652. };
  42653. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42654. GroundMesh.prototype._getFacetAt = function (x, z) {
  42655. // retrieve col and row from x, z coordinates in the ground local system
  42656. var subdivisionsX = this._subdivisionsX;
  42657. var subdivisionsY = this._subdivisionsY;
  42658. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42659. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42660. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42661. var facet;
  42662. if (z < quad.slope.x * x + quad.slope.y) {
  42663. facet = quad.facet1;
  42664. }
  42665. else {
  42666. facet = quad.facet2;
  42667. }
  42668. return facet;
  42669. };
  42670. // Creates and populates the heightMap array with "facet" elements :
  42671. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42672. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42673. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42674. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42675. // Returns the GroundMesh.
  42676. GroundMesh.prototype._initHeightQuads = function () {
  42677. var subdivisionsX = this._subdivisionsX;
  42678. var subdivisionsY = this._subdivisionsY;
  42679. this._heightQuads = new Array();
  42680. for (var row = 0; row < subdivisionsY; row++) {
  42681. for (var col = 0; col < subdivisionsX; col++) {
  42682. 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) };
  42683. this._heightQuads[row * subdivisionsX + col] = quad;
  42684. }
  42685. }
  42686. return this;
  42687. };
  42688. // Compute each quad element values and update the the heightMap array :
  42689. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42690. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42691. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42692. // Returns the GroundMesh.
  42693. GroundMesh.prototype._computeHeightQuads = function () {
  42694. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42695. var v1 = BABYLON.Tmp.Vector3[3];
  42696. var v2 = BABYLON.Tmp.Vector3[2];
  42697. var v3 = BABYLON.Tmp.Vector3[1];
  42698. var v4 = BABYLON.Tmp.Vector3[0];
  42699. var v1v2 = BABYLON.Tmp.Vector3[4];
  42700. var v1v3 = BABYLON.Tmp.Vector3[5];
  42701. var v1v4 = BABYLON.Tmp.Vector3[6];
  42702. var norm1 = BABYLON.Tmp.Vector3[7];
  42703. var norm2 = BABYLON.Tmp.Vector3[8];
  42704. var i = 0;
  42705. var j = 0;
  42706. var k = 0;
  42707. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42708. var h = 0;
  42709. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42710. var d2 = 0;
  42711. var subdivisionsX = this._subdivisionsX;
  42712. var subdivisionsY = this._subdivisionsY;
  42713. for (var row = 0; row < subdivisionsY; row++) {
  42714. for (var col = 0; col < subdivisionsX; col++) {
  42715. i = col * 3;
  42716. j = row * (subdivisionsX + 1) * 3;
  42717. k = (row + 1) * (subdivisionsX + 1) * 3;
  42718. v1.x = positions[j + i];
  42719. v1.y = positions[j + i + 1];
  42720. v1.z = positions[j + i + 2];
  42721. v2.x = positions[j + i + 3];
  42722. v2.y = positions[j + i + 4];
  42723. v2.z = positions[j + i + 5];
  42724. v3.x = positions[k + i];
  42725. v3.y = positions[k + i + 1];
  42726. v3.z = positions[k + i + 2];
  42727. v4.x = positions[k + i + 3];
  42728. v4.y = positions[k + i + 4];
  42729. v4.z = positions[k + i + 5];
  42730. // 2D slope V1V4
  42731. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42732. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42733. // facet equations :
  42734. // we compute each facet normal vector
  42735. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42736. // we compute the value d by applying the equation to v1 which belongs to the plane
  42737. // then we store the facet equation in a Vector4
  42738. v2.subtractToRef(v1, v1v2);
  42739. v3.subtractToRef(v1, v1v3);
  42740. v4.subtractToRef(v1, v1v4);
  42741. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42742. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42743. norm1.normalize();
  42744. norm2.normalize();
  42745. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42746. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42747. var quad = this._heightQuads[row * subdivisionsX + col];
  42748. quad.slope.copyFromFloats(cd, h);
  42749. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42750. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42751. }
  42752. }
  42753. return this;
  42754. };
  42755. GroundMesh.prototype.serialize = function (serializationObject) {
  42756. _super.prototype.serialize.call(this, serializationObject);
  42757. serializationObject.subdivisionsX = this._subdivisionsX;
  42758. serializationObject.subdivisionsY = this._subdivisionsY;
  42759. serializationObject.minX = this._minX;
  42760. serializationObject.maxX = this._maxX;
  42761. serializationObject.minZ = this._minZ;
  42762. serializationObject.maxZ = this._maxZ;
  42763. serializationObject.width = this._width;
  42764. serializationObject.height = this._height;
  42765. };
  42766. GroundMesh.Parse = function (parsedMesh, scene) {
  42767. var result = new GroundMesh(parsedMesh.name, scene);
  42768. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42769. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42770. result._minX = parsedMesh.minX;
  42771. result._maxX = parsedMesh.maxX;
  42772. result._minZ = parsedMesh.minZ;
  42773. result._maxZ = parsedMesh.maxZ;
  42774. result._width = parsedMesh.width;
  42775. result._height = parsedMesh.height;
  42776. return result;
  42777. };
  42778. return GroundMesh;
  42779. }(BABYLON.Mesh));
  42780. BABYLON.GroundMesh = GroundMesh;
  42781. })(BABYLON || (BABYLON = {}));
  42782. //# sourceMappingURL=babylon.groundMesh.js.map
  42783. var BABYLON;
  42784. (function (BABYLON) {
  42785. /**
  42786. * Creates an instance based on a source mesh.
  42787. */
  42788. var InstancedMesh = (function (_super) {
  42789. __extends(InstancedMesh, _super);
  42790. function InstancedMesh(name, source) {
  42791. var _this = _super.call(this, name, source.getScene()) || this;
  42792. source.instances.push(_this);
  42793. _this._sourceMesh = source;
  42794. _this.position.copyFrom(source.position);
  42795. _this.rotation.copyFrom(source.rotation);
  42796. _this.scaling.copyFrom(source.scaling);
  42797. if (source.rotationQuaternion) {
  42798. _this.rotationQuaternion = source.rotationQuaternion.clone();
  42799. }
  42800. _this.infiniteDistance = source.infiniteDistance;
  42801. _this.setPivotMatrix(source.getPivotMatrix());
  42802. _this.refreshBoundingInfo();
  42803. _this._syncSubMeshes();
  42804. return _this;
  42805. }
  42806. /**
  42807. * Returns the string "InstancedMesh".
  42808. */
  42809. InstancedMesh.prototype.getClassName = function () {
  42810. return "InstancedMesh";
  42811. };
  42812. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  42813. // Methods
  42814. get: function () {
  42815. return this._sourceMesh.receiveShadows;
  42816. },
  42817. enumerable: true,
  42818. configurable: true
  42819. });
  42820. Object.defineProperty(InstancedMesh.prototype, "material", {
  42821. get: function () {
  42822. return this._sourceMesh.material;
  42823. },
  42824. enumerable: true,
  42825. configurable: true
  42826. });
  42827. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  42828. get: function () {
  42829. return this._sourceMesh.visibility;
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  42835. get: function () {
  42836. return this._sourceMesh.skeleton;
  42837. },
  42838. enumerable: true,
  42839. configurable: true
  42840. });
  42841. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  42842. get: function () {
  42843. return this._sourceMesh.renderingGroupId;
  42844. },
  42845. enumerable: true,
  42846. configurable: true
  42847. });
  42848. /**
  42849. * Returns the total number of vertices (integer).
  42850. */
  42851. InstancedMesh.prototype.getTotalVertices = function () {
  42852. return this._sourceMesh.getTotalVertices();
  42853. };
  42854. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  42855. get: function () {
  42856. return this._sourceMesh;
  42857. },
  42858. enumerable: true,
  42859. configurable: true
  42860. });
  42861. /**
  42862. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  42863. */
  42864. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  42865. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  42866. };
  42867. /**
  42868. * Sets the vertex data of the mesh geometry for the requested `kind`.
  42869. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  42870. * The `data` are either a numeric array either a Float32Array.
  42871. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  42872. * 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).
  42873. * Note that a new underlying VertexBuffer object is created each call.
  42874. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  42875. *
  42876. * Possible `kind` values :
  42877. * - BABYLON.VertexBuffer.PositionKind
  42878. * - BABYLON.VertexBuffer.UVKind
  42879. * - BABYLON.VertexBuffer.UV2Kind
  42880. * - BABYLON.VertexBuffer.UV3Kind
  42881. * - BABYLON.VertexBuffer.UV4Kind
  42882. * - BABYLON.VertexBuffer.UV5Kind
  42883. * - BABYLON.VertexBuffer.UV6Kind
  42884. * - BABYLON.VertexBuffer.ColorKind
  42885. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42886. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42887. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42888. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42889. *
  42890. * Returns the Mesh.
  42891. */
  42892. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  42893. if (this.sourceMesh) {
  42894. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  42895. }
  42896. return this.sourceMesh;
  42897. };
  42898. /**
  42899. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  42900. * If the mesh has no geometry, it is simply returned as it is.
  42901. * The `data` are either a numeric array either a Float32Array.
  42902. * No new underlying VertexBuffer object is created.
  42903. * 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.
  42904. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  42905. *
  42906. * Possible `kind` values :
  42907. * - BABYLON.VertexBuffer.PositionKind
  42908. * - BABYLON.VertexBuffer.UVKind
  42909. * - BABYLON.VertexBuffer.UV2Kind
  42910. * - BABYLON.VertexBuffer.UV3Kind
  42911. * - BABYLON.VertexBuffer.UV4Kind
  42912. * - BABYLON.VertexBuffer.UV5Kind
  42913. * - BABYLON.VertexBuffer.UV6Kind
  42914. * - BABYLON.VertexBuffer.ColorKind
  42915. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42916. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42917. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42918. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42919. *
  42920. * Returns the Mesh.
  42921. */
  42922. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  42923. if (this.sourceMesh) {
  42924. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  42925. }
  42926. return this.sourceMesh;
  42927. };
  42928. /**
  42929. * Sets the mesh indices.
  42930. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  42931. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  42932. * This method creates a new index buffer each call.
  42933. * Returns the Mesh.
  42934. */
  42935. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  42936. if (this.sourceMesh) {
  42937. this.sourceMesh.setIndices(indices, totalVertices);
  42938. }
  42939. return this.sourceMesh;
  42940. };
  42941. /**
  42942. * Boolean : True if the mesh owns the requested kind of data.
  42943. */
  42944. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  42945. return this._sourceMesh.isVerticesDataPresent(kind);
  42946. };
  42947. /**
  42948. * Returns an array of indices (IndicesArray).
  42949. */
  42950. InstancedMesh.prototype.getIndices = function () {
  42951. return this._sourceMesh.getIndices();
  42952. };
  42953. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  42954. get: function () {
  42955. return this._sourceMesh._positions;
  42956. },
  42957. enumerable: true,
  42958. configurable: true
  42959. });
  42960. /**
  42961. * Sets a new updated BoundingInfo to the mesh.
  42962. * Returns the mesh.
  42963. */
  42964. InstancedMesh.prototype.refreshBoundingInfo = function () {
  42965. var meshBB = this._sourceMesh.getBoundingInfo();
  42966. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  42967. this._updateBoundingInfo();
  42968. return this;
  42969. };
  42970. InstancedMesh.prototype._preActivate = function () {
  42971. if (this._currentLOD) {
  42972. this._currentLOD._preActivate();
  42973. }
  42974. return this;
  42975. };
  42976. InstancedMesh.prototype._activate = function (renderId) {
  42977. if (this._currentLOD) {
  42978. this._currentLOD._registerInstanceForRenderId(this, renderId);
  42979. }
  42980. return this;
  42981. };
  42982. /**
  42983. * Returns the current associated LOD AbstractMesh.
  42984. */
  42985. InstancedMesh.prototype.getLOD = function (camera) {
  42986. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  42987. if (this._currentLOD === this.sourceMesh) {
  42988. return this;
  42989. }
  42990. return this._currentLOD;
  42991. };
  42992. InstancedMesh.prototype._syncSubMeshes = function () {
  42993. this.releaseSubMeshes();
  42994. if (this._sourceMesh.subMeshes) {
  42995. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  42996. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  42997. }
  42998. }
  42999. return this;
  43000. };
  43001. InstancedMesh.prototype._generatePointsArray = function () {
  43002. return this._sourceMesh._generatePointsArray();
  43003. };
  43004. /**
  43005. * Creates a new InstancedMesh from the current mesh.
  43006. * - name (string) : the cloned mesh name
  43007. * - newParent (optional Node) : the optional Node to parent the clone to.
  43008. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  43009. *
  43010. * Returns the clone.
  43011. */
  43012. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43013. var result = this._sourceMesh.createInstance(name);
  43014. // Deep copy
  43015. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  43016. // Bounding info
  43017. this.refreshBoundingInfo();
  43018. // Parent
  43019. if (newParent) {
  43020. result.parent = newParent;
  43021. }
  43022. if (!doNotCloneChildren) {
  43023. // Children
  43024. for (var index = 0; index < this.getScene().meshes.length; index++) {
  43025. var mesh = this.getScene().meshes[index];
  43026. if (mesh.parent === this) {
  43027. mesh.clone(mesh.name, result);
  43028. }
  43029. }
  43030. }
  43031. result.computeWorldMatrix(true);
  43032. return result;
  43033. };
  43034. /**
  43035. * Disposes the InstancedMesh.
  43036. * Returns nothing.
  43037. */
  43038. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  43039. // Remove from mesh
  43040. var index = this._sourceMesh.instances.indexOf(this);
  43041. this._sourceMesh.instances.splice(index, 1);
  43042. _super.prototype.dispose.call(this, doNotRecurse);
  43043. };
  43044. return InstancedMesh;
  43045. }(BABYLON.AbstractMesh));
  43046. BABYLON.InstancedMesh = InstancedMesh;
  43047. })(BABYLON || (BABYLON = {}));
  43048. //# sourceMappingURL=babylon.instancedMesh.js.map
  43049. /// <reference path="babylon.mesh.ts" />
  43050. var BABYLON;
  43051. (function (BABYLON) {
  43052. var LinesMesh = (function (_super) {
  43053. __extends(LinesMesh, _super);
  43054. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  43055. if (parent === void 0) { parent = null; }
  43056. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43057. _this.useVertexColor = useVertexColor;
  43058. _this.color = new BABYLON.Color3(1, 1, 1);
  43059. _this.alpha = 1;
  43060. if (source) {
  43061. _this.color = source.color.clone();
  43062. _this.alpha = source.alpha;
  43063. _this.useVertexColor = source.useVertexColor;
  43064. }
  43065. _this._intersectionThreshold = 0.1;
  43066. var options = {
  43067. attributes: [BABYLON.VertexBuffer.PositionKind],
  43068. uniforms: ["world", "viewProjection"],
  43069. needAlphaBlending: false,
  43070. };
  43071. if (!useVertexColor) {
  43072. options.uniforms.push("color");
  43073. options.needAlphaBlending = true;
  43074. }
  43075. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  43076. return _this;
  43077. }
  43078. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43079. /**
  43080. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43081. * This margin is expressed in world space coordinates, so its value may vary.
  43082. * Default value is 0.1
  43083. * @returns the intersection Threshold value.
  43084. */
  43085. get: function () {
  43086. return this._intersectionThreshold;
  43087. },
  43088. /**
  43089. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43090. * This margin is expressed in world space coordinates, so its value may vary.
  43091. * @param value the new threshold to apply
  43092. */
  43093. set: function (value) {
  43094. if (this._intersectionThreshold === value) {
  43095. return;
  43096. }
  43097. this._intersectionThreshold = value;
  43098. if (this.geometry) {
  43099. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43100. }
  43101. },
  43102. enumerable: true,
  43103. configurable: true
  43104. });
  43105. /**
  43106. * Returns the string "LineMesh"
  43107. */
  43108. LinesMesh.prototype.getClassName = function () {
  43109. return "LinesMesh";
  43110. };
  43111. Object.defineProperty(LinesMesh.prototype, "material", {
  43112. get: function () {
  43113. return this._colorShader;
  43114. },
  43115. enumerable: true,
  43116. configurable: true
  43117. });
  43118. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43119. get: function () {
  43120. return false;
  43121. },
  43122. enumerable: true,
  43123. configurable: true
  43124. });
  43125. LinesMesh.prototype.createInstance = function (name) {
  43126. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  43127. return null;
  43128. };
  43129. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  43130. // VBOs
  43131. this._geometry._bind(this._colorShader.getEffect());
  43132. // Color
  43133. if (!this.useVertexColor) {
  43134. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  43135. }
  43136. return this;
  43137. };
  43138. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  43139. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  43140. return this;
  43141. }
  43142. var engine = this.getScene().getEngine();
  43143. // Draw order
  43144. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  43145. return this;
  43146. };
  43147. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43148. this._colorShader.dispose();
  43149. _super.prototype.dispose.call(this, doNotRecurse);
  43150. };
  43151. /**
  43152. * Returns a new LineMesh object cloned from the current one.
  43153. */
  43154. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43155. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43156. };
  43157. return LinesMesh;
  43158. }(BABYLON.Mesh));
  43159. BABYLON.LinesMesh = LinesMesh;
  43160. })(BABYLON || (BABYLON = {}));
  43161. //# sourceMappingURL=babylon.linesMesh.js.map
  43162. var BABYLON;
  43163. (function (BABYLON) {
  43164. var ShaderMaterial = (function (_super) {
  43165. __extends(ShaderMaterial, _super);
  43166. function ShaderMaterial(name, scene, shaderPath, options) {
  43167. var _this = _super.call(this, name, scene) || this;
  43168. _this._textures = {};
  43169. _this._textureArrays = {};
  43170. _this._floats = {};
  43171. _this._floatsArrays = {};
  43172. _this._colors3 = {};
  43173. _this._colors3Arrays = {};
  43174. _this._colors4 = {};
  43175. _this._vectors2 = {};
  43176. _this._vectors3 = {};
  43177. _this._vectors4 = {};
  43178. _this._matrices = {};
  43179. _this._matrices3x3 = {};
  43180. _this._matrices2x2 = {};
  43181. _this._vectors3Arrays = {};
  43182. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  43183. _this._shaderPath = shaderPath;
  43184. options.needAlphaBlending = options.needAlphaBlending || false;
  43185. options.needAlphaTesting = options.needAlphaTesting || false;
  43186. options.attributes = options.attributes || ["position", "normal", "uv"];
  43187. options.uniforms = options.uniforms || ["worldViewProjection"];
  43188. options.uniformBuffers = options.uniformBuffers || [];
  43189. options.samplers = options.samplers || [];
  43190. options.defines = options.defines || [];
  43191. _this._options = options;
  43192. return _this;
  43193. }
  43194. ShaderMaterial.prototype.getClassName = function () {
  43195. return "ShaderMaterial";
  43196. };
  43197. ShaderMaterial.prototype.needAlphaBlending = function () {
  43198. return this._options.needAlphaBlending;
  43199. };
  43200. ShaderMaterial.prototype.needAlphaTesting = function () {
  43201. return this._options.needAlphaTesting;
  43202. };
  43203. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  43204. if (this._options.uniforms.indexOf(uniformName) === -1) {
  43205. this._options.uniforms.push(uniformName);
  43206. }
  43207. };
  43208. ShaderMaterial.prototype.setTexture = function (name, texture) {
  43209. if (this._options.samplers.indexOf(name) === -1) {
  43210. this._options.samplers.push(name);
  43211. }
  43212. this._textures[name] = texture;
  43213. return this;
  43214. };
  43215. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  43216. if (this._options.samplers.indexOf(name) === -1) {
  43217. this._options.samplers.push(name);
  43218. }
  43219. this._checkUniform(name);
  43220. this._textureArrays[name] = textures;
  43221. return this;
  43222. };
  43223. ShaderMaterial.prototype.setFloat = function (name, value) {
  43224. this._checkUniform(name);
  43225. this._floats[name] = value;
  43226. return this;
  43227. };
  43228. ShaderMaterial.prototype.setFloats = function (name, value) {
  43229. this._checkUniform(name);
  43230. this._floatsArrays[name] = value;
  43231. return this;
  43232. };
  43233. ShaderMaterial.prototype.setColor3 = function (name, value) {
  43234. this._checkUniform(name);
  43235. this._colors3[name] = value;
  43236. return this;
  43237. };
  43238. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  43239. this._checkUniform(name);
  43240. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  43241. color.toArray(arr, arr.length);
  43242. return arr;
  43243. }, []);
  43244. return this;
  43245. };
  43246. ShaderMaterial.prototype.setColor4 = function (name, value) {
  43247. this._checkUniform(name);
  43248. this._colors4[name] = value;
  43249. return this;
  43250. };
  43251. ShaderMaterial.prototype.setVector2 = function (name, value) {
  43252. this._checkUniform(name);
  43253. this._vectors2[name] = value;
  43254. return this;
  43255. };
  43256. ShaderMaterial.prototype.setVector3 = function (name, value) {
  43257. this._checkUniform(name);
  43258. this._vectors3[name] = value;
  43259. return this;
  43260. };
  43261. ShaderMaterial.prototype.setVector4 = function (name, value) {
  43262. this._checkUniform(name);
  43263. this._vectors4[name] = value;
  43264. return this;
  43265. };
  43266. ShaderMaterial.prototype.setMatrix = function (name, value) {
  43267. this._checkUniform(name);
  43268. this._matrices[name] = value;
  43269. return this;
  43270. };
  43271. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  43272. this._checkUniform(name);
  43273. this._matrices3x3[name] = value;
  43274. return this;
  43275. };
  43276. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  43277. this._checkUniform(name);
  43278. this._matrices2x2[name] = value;
  43279. return this;
  43280. };
  43281. ShaderMaterial.prototype.setArray3 = function (name, value) {
  43282. this._checkUniform(name);
  43283. this._vectors3Arrays[name] = value;
  43284. return this;
  43285. };
  43286. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  43287. if (!mesh) {
  43288. return true;
  43289. }
  43290. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  43291. return false;
  43292. }
  43293. return false;
  43294. };
  43295. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  43296. var scene = this.getScene();
  43297. var engine = scene.getEngine();
  43298. if (!this.checkReadyOnEveryCall) {
  43299. if (this._renderId === scene.getRenderId()) {
  43300. if (this._checkCache(scene, mesh, useInstances)) {
  43301. return true;
  43302. }
  43303. }
  43304. }
  43305. // Instances
  43306. var defines = [];
  43307. var attribs = [];
  43308. var fallbacks = new BABYLON.EffectFallbacks();
  43309. if (useInstances) {
  43310. defines.push("#define INSTANCES");
  43311. }
  43312. for (var index = 0; index < this._options.defines.length; index++) {
  43313. defines.push(this._options.defines[index]);
  43314. }
  43315. for (var index = 0; index < this._options.attributes.length; index++) {
  43316. attribs.push(this._options.attributes[index]);
  43317. }
  43318. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  43319. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43320. defines.push("#define VERTEXCOLOR");
  43321. }
  43322. // Bones
  43323. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43324. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43325. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43326. if (mesh.numBoneInfluencers > 4) {
  43327. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43328. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43329. }
  43330. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43331. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43332. fallbacks.addCPUSkinningFallback(0, mesh);
  43333. if (this._options.uniforms.indexOf("mBones") === -1) {
  43334. this._options.uniforms.push("mBones");
  43335. }
  43336. }
  43337. else {
  43338. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43339. }
  43340. // Textures
  43341. for (var name in this._textures) {
  43342. if (!this._textures[name].isReady()) {
  43343. return false;
  43344. }
  43345. }
  43346. // Alpha test
  43347. if (engine.getAlphaTesting()) {
  43348. defines.push("#define ALPHATEST");
  43349. }
  43350. var previousEffect = this._effect;
  43351. var join = defines.join("\n");
  43352. this._effect = engine.createEffect(this._shaderPath, {
  43353. attributes: attribs,
  43354. uniformsNames: this._options.uniforms,
  43355. uniformBuffersNames: this._options.uniformBuffers,
  43356. samplers: this._options.samplers,
  43357. defines: join,
  43358. fallbacks: fallbacks,
  43359. onCompiled: this.onCompiled,
  43360. onError: this.onError
  43361. }, engine);
  43362. if (!this._effect.isReady()) {
  43363. return false;
  43364. }
  43365. if (previousEffect !== this._effect) {
  43366. scene.resetCachedMaterial();
  43367. }
  43368. this._renderId = scene.getRenderId();
  43369. return true;
  43370. };
  43371. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43372. var scene = this.getScene();
  43373. if (this._options.uniforms.indexOf("world") !== -1) {
  43374. this._effect.setMatrix("world", world);
  43375. }
  43376. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43377. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43378. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43379. }
  43380. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43381. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43382. }
  43383. };
  43384. ShaderMaterial.prototype.bind = function (world, mesh) {
  43385. // Std values
  43386. this.bindOnlyWorldMatrix(world);
  43387. if (this.getScene().getCachedMaterial() !== this) {
  43388. if (this._options.uniforms.indexOf("view") !== -1) {
  43389. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43390. }
  43391. if (this._options.uniforms.indexOf("projection") !== -1) {
  43392. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43393. }
  43394. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43395. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43396. }
  43397. // Bones
  43398. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  43399. var name;
  43400. // Texture
  43401. for (name in this._textures) {
  43402. this._effect.setTexture(name, this._textures[name]);
  43403. }
  43404. // Texture arrays
  43405. for (name in this._textureArrays) {
  43406. this._effect.setTextureArray(name, this._textureArrays[name]);
  43407. }
  43408. // Float
  43409. for (name in this._floats) {
  43410. this._effect.setFloat(name, this._floats[name]);
  43411. }
  43412. // Float s
  43413. for (name in this._floatsArrays) {
  43414. this._effect.setArray(name, this._floatsArrays[name]);
  43415. }
  43416. // Color3
  43417. for (name in this._colors3) {
  43418. this._effect.setColor3(name, this._colors3[name]);
  43419. }
  43420. for (name in this._colors3Arrays) {
  43421. this._effect.setArray3(name, this._colors3Arrays[name]);
  43422. }
  43423. // Color4
  43424. for (name in this._colors4) {
  43425. var color = this._colors4[name];
  43426. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43427. }
  43428. // Vector2
  43429. for (name in this._vectors2) {
  43430. this._effect.setVector2(name, this._vectors2[name]);
  43431. }
  43432. // Vector3
  43433. for (name in this._vectors3) {
  43434. this._effect.setVector3(name, this._vectors3[name]);
  43435. }
  43436. // Vector4
  43437. for (name in this._vectors4) {
  43438. this._effect.setVector4(name, this._vectors4[name]);
  43439. }
  43440. // Matrix
  43441. for (name in this._matrices) {
  43442. this._effect.setMatrix(name, this._matrices[name]);
  43443. }
  43444. // Matrix 3x3
  43445. for (name in this._matrices3x3) {
  43446. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43447. }
  43448. // Matrix 2x2
  43449. for (name in this._matrices2x2) {
  43450. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43451. }
  43452. // Vector3Array
  43453. for (name in this._vectors3Arrays) {
  43454. this._effect.setArray3(name, this._vectors3Arrays[name]);
  43455. }
  43456. }
  43457. this._afterBind(mesh);
  43458. };
  43459. ShaderMaterial.prototype.getActiveTextures = function () {
  43460. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43461. for (var name in this._textures) {
  43462. activeTextures.push(this._textures[name]);
  43463. }
  43464. for (var name in this._textureArrays) {
  43465. var array = this._textureArrays[name];
  43466. for (var index = 0; index < array.length; index++) {
  43467. activeTextures.push(array[index]);
  43468. }
  43469. }
  43470. return activeTextures;
  43471. };
  43472. ShaderMaterial.prototype.hasTexture = function (texture) {
  43473. if (_super.prototype.hasTexture.call(this, texture)) {
  43474. return true;
  43475. }
  43476. for (var name in this._textures) {
  43477. if (this._textures[name] === texture) {
  43478. return true;
  43479. }
  43480. }
  43481. for (var name in this._textureArrays) {
  43482. var array = this._textureArrays[name];
  43483. for (var index = 0; index < array.length; index++) {
  43484. if (array[index] === texture) {
  43485. return true;
  43486. }
  43487. }
  43488. }
  43489. return false;
  43490. };
  43491. ShaderMaterial.prototype.clone = function (name) {
  43492. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43493. return newShaderMaterial;
  43494. };
  43495. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43496. if (forceDisposeTextures) {
  43497. var name;
  43498. for (name in this._textures) {
  43499. this._textures[name].dispose();
  43500. }
  43501. for (name in this._textureArrays) {
  43502. var array = this._textureArrays[name];
  43503. for (var index = 0; index < array.length; index++) {
  43504. array[index].dispose();
  43505. }
  43506. }
  43507. }
  43508. this._textures = {};
  43509. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43510. };
  43511. ShaderMaterial.prototype.serialize = function () {
  43512. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43513. serializationObject.customType = "BABYLON.ShaderMaterial";
  43514. serializationObject.options = this._options;
  43515. serializationObject.shaderPath = this._shaderPath;
  43516. var name;
  43517. // Texture
  43518. serializationObject.textures = {};
  43519. for (name in this._textures) {
  43520. serializationObject.textures[name] = this._textures[name].serialize();
  43521. }
  43522. // Texture arrays
  43523. serializationObject.textureArrays = {};
  43524. for (name in this._textureArrays) {
  43525. serializationObject.textureArrays[name] = [];
  43526. var array = this._textureArrays[name];
  43527. for (var index = 0; index < array.length; index++) {
  43528. serializationObject.textureArrays[name].push(array[index].serialize());
  43529. }
  43530. }
  43531. // Float
  43532. serializationObject.floats = {};
  43533. for (name in this._floats) {
  43534. serializationObject.floats[name] = this._floats[name];
  43535. }
  43536. // Float s
  43537. serializationObject.floatArrays = {};
  43538. for (name in this._floatsArrays) {
  43539. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43540. }
  43541. // Color3
  43542. serializationObject.colors3 = {};
  43543. for (name in this._colors3) {
  43544. serializationObject.colors3[name] = this._colors3[name].asArray();
  43545. }
  43546. // Color3 array
  43547. serializationObject.colors3Arrays = {};
  43548. for (name in this._colors3Arrays) {
  43549. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  43550. }
  43551. // Color4
  43552. serializationObject.colors4 = {};
  43553. for (name in this._colors4) {
  43554. serializationObject.colors4[name] = this._colors4[name].asArray();
  43555. }
  43556. // Vector2
  43557. serializationObject.vectors2 = {};
  43558. for (name in this._vectors2) {
  43559. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43560. }
  43561. // Vector3
  43562. serializationObject.vectors3 = {};
  43563. for (name in this._vectors3) {
  43564. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43565. }
  43566. // Vector4
  43567. serializationObject.vectors4 = {};
  43568. for (name in this._vectors4) {
  43569. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43570. }
  43571. // Matrix
  43572. serializationObject.matrices = {};
  43573. for (name in this._matrices) {
  43574. serializationObject.matrices[name] = this._matrices[name].asArray();
  43575. }
  43576. // Matrix 3x3
  43577. serializationObject.matrices3x3 = {};
  43578. for (name in this._matrices3x3) {
  43579. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43580. }
  43581. // Matrix 2x2
  43582. serializationObject.matrices2x2 = {};
  43583. for (name in this._matrices2x2) {
  43584. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43585. }
  43586. // Vector3Array
  43587. serializationObject.vectors3Arrays = {};
  43588. for (name in this._vectors3Arrays) {
  43589. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  43590. }
  43591. return serializationObject;
  43592. };
  43593. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43594. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43595. var name;
  43596. // Texture
  43597. for (name in source.textures) {
  43598. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43599. }
  43600. // Texture arrays
  43601. for (name in source.textureArrays) {
  43602. var array = source.textureArrays[name];
  43603. var textureArray = new Array();
  43604. for (var index = 0; index < array.length; index++) {
  43605. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  43606. }
  43607. material.setTextureArray(name, textureArray);
  43608. }
  43609. // Float
  43610. for (name in source.floats) {
  43611. material.setFloat(name, source.floats[name]);
  43612. }
  43613. // Float s
  43614. for (name in source.floatsArrays) {
  43615. material.setFloats(name, source.floatsArrays[name]);
  43616. }
  43617. // Color3
  43618. for (name in source.colors3) {
  43619. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43620. }
  43621. // Color3 arrays
  43622. for (name in source.colors3Arrays) {
  43623. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  43624. if (i % 3 === 0) {
  43625. arr.push([num]);
  43626. }
  43627. else {
  43628. arr[arr.length - 1].push(num);
  43629. }
  43630. return arr;
  43631. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  43632. material.setColor3Array(name, colors);
  43633. }
  43634. // Color4
  43635. for (name in source.colors4) {
  43636. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43637. }
  43638. // Vector2
  43639. for (name in source.vectors2) {
  43640. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43641. }
  43642. // Vector3
  43643. for (name in source.vectors3) {
  43644. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43645. }
  43646. // Vector4
  43647. for (name in source.vectors4) {
  43648. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43649. }
  43650. // Matrix
  43651. for (name in source.matrices) {
  43652. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43653. }
  43654. // Matrix 3x3
  43655. for (name in source.matrices3x3) {
  43656. material.setMatrix3x3(name, source.matrices3x3[name]);
  43657. }
  43658. // Matrix 2x2
  43659. for (name in source.matrices2x2) {
  43660. material.setMatrix2x2(name, source.matrices2x2[name]);
  43661. }
  43662. // Vector3Array
  43663. for (name in source.vectors3Arrays) {
  43664. material.setArray3(name, source.vectors3Arrays[name]);
  43665. }
  43666. return material;
  43667. };
  43668. return ShaderMaterial;
  43669. }(BABYLON.Material));
  43670. BABYLON.ShaderMaterial = ShaderMaterial;
  43671. })(BABYLON || (BABYLON = {}));
  43672. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43673. var BABYLON;
  43674. (function (BABYLON) {
  43675. var MeshBuilder = (function () {
  43676. function MeshBuilder() {
  43677. }
  43678. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  43679. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  43680. return BABYLON.Mesh.DOUBLESIDE;
  43681. }
  43682. if (orientation === undefined || orientation === null) {
  43683. return BABYLON.Mesh.FRONTSIDE;
  43684. }
  43685. return orientation;
  43686. };
  43687. /**
  43688. * Creates a box mesh.
  43689. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  43690. * The parameter `size` sets the size (float) of each box side (default 1).
  43691. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  43692. * 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).
  43693. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43694. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43695. * 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).
  43696. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43698. */
  43699. MeshBuilder.CreateBox = function (name, options, scene) {
  43700. var box = new BABYLON.Mesh(name, scene);
  43701. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43702. box.sideOrientation = options.sideOrientation;
  43703. var vertexData = BABYLON.VertexData.CreateBox(options);
  43704. vertexData.applyToMesh(box, options.updatable);
  43705. return box;
  43706. };
  43707. /**
  43708. * Creates a sphere mesh.
  43709. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  43710. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  43711. * 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`).
  43712. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  43713. * 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
  43714. * 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).
  43715. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43716. * 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).
  43717. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43718. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43719. */
  43720. MeshBuilder.CreateSphere = function (name, options, scene) {
  43721. var sphere = new BABYLON.Mesh(name, scene);
  43722. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43723. sphere.sideOrientation = options.sideOrientation;
  43724. var vertexData = BABYLON.VertexData.CreateSphere(options);
  43725. vertexData.applyToMesh(sphere, options.updatable);
  43726. return sphere;
  43727. };
  43728. /**
  43729. * Creates a plane polygonal mesh. By default, this is a disc.
  43730. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  43731. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  43732. * 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.
  43733. * 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
  43734. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43735. * 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).
  43736. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43737. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43738. */
  43739. MeshBuilder.CreateDisc = function (name, options, scene) {
  43740. var disc = new BABYLON.Mesh(name, scene);
  43741. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43742. disc.sideOrientation = options.sideOrientation;
  43743. var vertexData = BABYLON.VertexData.CreateDisc(options);
  43744. vertexData.applyToMesh(disc, options.updatable);
  43745. return disc;
  43746. };
  43747. /**
  43748. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  43749. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  43750. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  43751. * 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`).
  43752. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  43753. * 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.
  43754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43755. * 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).
  43756. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43758. */
  43759. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  43760. var sphere = new BABYLON.Mesh(name, scene);
  43761. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43762. sphere.sideOrientation = options.sideOrientation;
  43763. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  43764. vertexData.applyToMesh(sphere, options.updatable);
  43765. return sphere;
  43766. };
  43767. ;
  43768. /**
  43769. * Creates a ribbon mesh.
  43770. * 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.
  43771. *
  43772. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  43773. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  43774. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  43775. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  43776. * 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.
  43777. * 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.
  43778. * 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
  43779. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43780. * 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).
  43781. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43782. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43783. * 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.
  43784. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  43785. * 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
  43786. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  43787. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  43788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43789. */
  43790. MeshBuilder.CreateRibbon = function (name, options, scene) {
  43791. var pathArray = options.pathArray;
  43792. var closeArray = options.closeArray;
  43793. var closePath = options.closePath;
  43794. var offset = options.offset;
  43795. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43796. var instance = options.instance;
  43797. var updatable = options.updatable;
  43798. if (instance) {
  43799. // positionFunction : ribbon case
  43800. // only pathArray and sideOrientation parameters are taken into account for positions update
  43801. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  43802. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  43803. var positionFunction = function (positions) {
  43804. var minlg = pathArray[0].length;
  43805. var i = 0;
  43806. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  43807. for (var si = 1; si <= ns; si++) {
  43808. for (var p = 0; p < pathArray.length; p++) {
  43809. var path = pathArray[p];
  43810. var l = path.length;
  43811. minlg = (minlg < l) ? minlg : l;
  43812. var j = 0;
  43813. while (j < minlg) {
  43814. positions[i] = path[j].x;
  43815. positions[i + 1] = path[j].y;
  43816. positions[i + 2] = path[j].z;
  43817. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  43818. BABYLON.Tmp.Vector3[0].x = path[j].x;
  43819. }
  43820. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  43821. BABYLON.Tmp.Vector3[1].x = path[j].x;
  43822. }
  43823. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  43824. BABYLON.Tmp.Vector3[0].y = path[j].y;
  43825. }
  43826. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  43827. BABYLON.Tmp.Vector3[1].y = path[j].y;
  43828. }
  43829. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  43830. BABYLON.Tmp.Vector3[0].z = path[j].z;
  43831. }
  43832. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  43833. BABYLON.Tmp.Vector3[1].z = path[j].z;
  43834. }
  43835. j++;
  43836. i += 3;
  43837. }
  43838. if (instance._closePath) {
  43839. positions[i] = path[0].x;
  43840. positions[i + 1] = path[0].y;
  43841. positions[i + 2] = path[0].z;
  43842. i += 3;
  43843. }
  43844. }
  43845. }
  43846. };
  43847. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43848. positionFunction(positions);
  43849. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  43850. instance._boundingInfo.update(instance._worldMatrix);
  43851. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  43852. if (options.colors) {
  43853. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43854. for (var c = 0; c < options.colors.length; c++) {
  43855. colors[c * 4] = options.colors[c].r;
  43856. colors[c * 4 + 1] = options.colors[c].g;
  43857. colors[c * 4 + 2] = options.colors[c].b;
  43858. colors[c * 4 + 3] = options.colors[c].a;
  43859. }
  43860. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  43861. }
  43862. if (options.uvs) {
  43863. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43864. for (var i = 0; i < options.uvs.length; i++) {
  43865. uvs[i * 2] = options.uvs[i].x;
  43866. uvs[i * 2 + 1] = options.uvs[i].y;
  43867. }
  43868. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  43869. }
  43870. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  43871. var indices = instance.getIndices();
  43872. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43873. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  43874. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  43875. if (instance._closePath) {
  43876. var indexFirst = 0;
  43877. var indexLast = 0;
  43878. for (var p = 0; p < pathArray.length; p++) {
  43879. indexFirst = instance._idx[p] * 3;
  43880. if (p + 1 < pathArray.length) {
  43881. indexLast = (instance._idx[p + 1] - 1) * 3;
  43882. }
  43883. else {
  43884. indexLast = normals.length - 3;
  43885. }
  43886. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  43887. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  43888. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  43889. normals[indexLast] = normals[indexFirst];
  43890. normals[indexLast + 1] = normals[indexFirst + 1];
  43891. normals[indexLast + 2] = normals[indexFirst + 2];
  43892. }
  43893. }
  43894. if (!(instance.areNormalsFrozen)) {
  43895. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  43896. }
  43897. }
  43898. return instance;
  43899. }
  43900. else {
  43901. var ribbon = new BABYLON.Mesh(name, scene);
  43902. ribbon.sideOrientation = sideOrientation;
  43903. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  43904. if (closePath) {
  43905. ribbon._idx = vertexData._idx;
  43906. }
  43907. ribbon._closePath = closePath;
  43908. ribbon._closeArray = closeArray;
  43909. vertexData.applyToMesh(ribbon, updatable);
  43910. return ribbon;
  43911. }
  43912. };
  43913. /**
  43914. * Creates a cylinder or a cone mesh.
  43915. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  43916. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  43917. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  43918. * 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.
  43919. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  43920. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  43921. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  43922. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  43923. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  43924. * 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).
  43925. * 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
  43926. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  43927. * 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
  43928. * 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.
  43929. * If `enclose` is false, a ring surface is one element.
  43930. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  43931. * 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
  43932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43933. * 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).
  43934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43936. */
  43937. MeshBuilder.CreateCylinder = function (name, options, scene) {
  43938. var cylinder = new BABYLON.Mesh(name, scene);
  43939. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43940. cylinder.sideOrientation = options.sideOrientation;
  43941. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  43942. vertexData.applyToMesh(cylinder, options.updatable);
  43943. return cylinder;
  43944. };
  43945. /**
  43946. * Creates a torus mesh.
  43947. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  43948. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  43949. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  43950. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  43951. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43952. * 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).
  43953. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43955. */
  43956. MeshBuilder.CreateTorus = function (name, options, scene) {
  43957. var torus = new BABYLON.Mesh(name, scene);
  43958. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43959. torus.sideOrientation = options.sideOrientation;
  43960. var vertexData = BABYLON.VertexData.CreateTorus(options);
  43961. vertexData.applyToMesh(torus, options.updatable);
  43962. return torus;
  43963. };
  43964. /**
  43965. * Creates a torus knot mesh.
  43966. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  43967. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  43968. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  43969. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  43970. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  43971. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43972. * 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).
  43973. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43975. */
  43976. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  43977. var torusKnot = new BABYLON.Mesh(name, scene);
  43978. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43979. torusKnot.sideOrientation = options.sideOrientation;
  43980. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  43981. vertexData.applyToMesh(torusKnot, options.updatable);
  43982. return torusKnot;
  43983. };
  43984. /**
  43985. * Creates a line system mesh.
  43986. * A line system is a pool of many lines gathered in a single mesh.
  43987. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  43988. * 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.
  43989. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  43990. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  43991. * 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
  43992. * 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
  43993. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  43994. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43995. */
  43996. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  43997. var instance = options.instance;
  43998. var lines = options.lines;
  43999. if (instance) {
  44000. var positionFunction = function (positions) {
  44001. var i = 0;
  44002. for (var l = 0; l < lines.length; l++) {
  44003. var points = lines[l];
  44004. for (var p = 0; p < points.length; p++) {
  44005. positions[i] = points[p].x;
  44006. positions[i + 1] = points[p].y;
  44007. positions[i + 2] = points[p].z;
  44008. i += 3;
  44009. }
  44010. }
  44011. };
  44012. instance.updateMeshPositions(positionFunction, false);
  44013. return instance;
  44014. }
  44015. // line system creation
  44016. var lineSystem = new BABYLON.LinesMesh(name, scene);
  44017. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  44018. vertexData.applyToMesh(lineSystem, options.updatable);
  44019. return lineSystem;
  44020. };
  44021. /**
  44022. * Creates a line mesh.
  44023. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  44024. * 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.
  44025. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  44026. * The parameter `points` is an array successive Vector3.
  44027. * 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
  44028. * When updating an instance, remember that only point positions can change, not the number of points.
  44029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44030. */
  44031. MeshBuilder.CreateLines = function (name, options, scene) {
  44032. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  44033. return lines;
  44034. };
  44035. /**
  44036. * Creates a dashed line mesh.
  44037. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  44038. * 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.
  44039. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  44040. * The parameter `points` is an array successive Vector3.
  44041. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  44042. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  44043. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  44044. * 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
  44045. * When updating an instance, remember that only point positions can change, not the number of points.
  44046. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44047. */
  44048. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  44049. var points = options.points;
  44050. var instance = options.instance;
  44051. var gapSize = options.gapSize || 1;
  44052. var dashSize = options.dashSize || 3;
  44053. if (instance) {
  44054. var positionFunction = function (positions) {
  44055. var curvect = BABYLON.Vector3.Zero();
  44056. var nbSeg = positions.length / 6;
  44057. var lg = 0;
  44058. var nb = 0;
  44059. var shft = 0;
  44060. var dashshft = 0;
  44061. var curshft = 0;
  44062. var p = 0;
  44063. var i = 0;
  44064. var j = 0;
  44065. for (i = 0; i < points.length - 1; i++) {
  44066. points[i + 1].subtractToRef(points[i], curvect);
  44067. lg += curvect.length();
  44068. }
  44069. shft = lg / nbSeg;
  44070. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  44071. for (i = 0; i < points.length - 1; i++) {
  44072. points[i + 1].subtractToRef(points[i], curvect);
  44073. nb = Math.floor(curvect.length() / shft);
  44074. curvect.normalize();
  44075. j = 0;
  44076. while (j < nb && p < positions.length) {
  44077. curshft = shft * j;
  44078. positions[p] = points[i].x + curshft * curvect.x;
  44079. positions[p + 1] = points[i].y + curshft * curvect.y;
  44080. positions[p + 2] = points[i].z + curshft * curvect.z;
  44081. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  44082. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  44083. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  44084. p += 6;
  44085. j++;
  44086. }
  44087. }
  44088. while (p < positions.length) {
  44089. positions[p] = points[i].x;
  44090. positions[p + 1] = points[i].y;
  44091. positions[p + 2] = points[i].z;
  44092. p += 3;
  44093. }
  44094. };
  44095. instance.updateMeshPositions(positionFunction, false);
  44096. return instance;
  44097. }
  44098. // dashed lines creation
  44099. var dashedLines = new BABYLON.LinesMesh(name, scene);
  44100. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  44101. vertexData.applyToMesh(dashedLines, options.updatable);
  44102. dashedLines.dashSize = dashSize;
  44103. dashedLines.gapSize = gapSize;
  44104. return dashedLines;
  44105. };
  44106. /**
  44107. * Creates an extruded shape mesh.
  44108. * 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.
  44109. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  44110. *
  44111. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  44112. * 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
  44113. * extruded along the Z axis.
  44114. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  44115. * 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.
  44116. * The parameter `scale` (float, default 1) is the value to scale the shape.
  44117. * 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
  44118. * 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
  44119. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  44120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44121. * 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).
  44122. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44123. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44125. */
  44126. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  44127. var path = options.path;
  44128. var shape = options.shape;
  44129. var scale = options.scale || 1;
  44130. var rotation = options.rotation || 0;
  44131. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  44132. var updatable = options.updatable;
  44133. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44134. var instance = options.instance;
  44135. var invertUV = options.invertUV || false;
  44136. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  44137. };
  44138. /**
  44139. * Creates an custom extruded shape mesh.
  44140. * 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.
  44141. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  44142. *
  44143. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  44144. * 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
  44145. * extruded along the Z axis.
  44146. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  44147. * 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
  44148. * and the distance of this point from the begining of the path :
  44149. * ```javascript
  44150. * var rotationFunction = function(i, distance) {
  44151. * // do things
  44152. * return rotationValue; }
  44153. * ```
  44154. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  44155. * 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
  44156. * and the distance of this point from the begining of the path :
  44157. * ```javascript
  44158. * var scaleFunction = function(i, distance) {
  44159. * // do things
  44160. * return scaleValue;}
  44161. * ```
  44162. * It must returns a float value that will be the scale value applied to the shape on each path point.
  44163. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  44164. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  44165. * 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
  44166. * 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
  44167. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  44168. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44169. * 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).
  44170. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44171. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44173. */
  44174. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  44175. var path = options.path;
  44176. var shape = options.shape;
  44177. var scaleFunction = options.scaleFunction || (function () { return 1; });
  44178. var rotationFunction = options.rotationFunction || (function () { return 0; });
  44179. var ribbonCloseArray = options.ribbonCloseArray || false;
  44180. var ribbonClosePath = options.ribbonClosePath || false;
  44181. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  44182. var updatable = options.updatable;
  44183. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44184. var instance = options.instance;
  44185. var invertUV = options.invertUV || false;
  44186. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  44187. };
  44188. /**
  44189. * Creates lathe mesh.
  44190. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  44191. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  44192. *
  44193. * 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
  44194. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  44195. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  44196. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  44197. * 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.
  44198. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  44199. * 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
  44200. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44201. * 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).
  44202. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44203. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44205. */
  44206. MeshBuilder.CreateLathe = function (name, options, scene) {
  44207. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  44208. var closed = (options.closed === undefined) ? true : options.closed;
  44209. var shape = options.shape;
  44210. var radius = options.radius || 1;
  44211. var tessellation = options.tessellation || 64;
  44212. var updatable = options.updatable;
  44213. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44214. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44215. var pi2 = Math.PI * 2;
  44216. var paths = new Array();
  44217. var invertUV = options.invertUV || false;
  44218. var i = 0;
  44219. var p = 0;
  44220. var step = pi2 / tessellation * arc;
  44221. var rotated;
  44222. var path = new Array();
  44223. ;
  44224. for (i = 0; i <= tessellation; i++) {
  44225. var path = [];
  44226. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  44227. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  44228. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  44229. }
  44230. for (p = 0; p < shape.length; p++) {
  44231. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  44232. path.push(rotated);
  44233. }
  44234. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  44235. 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));
  44236. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  44237. }
  44238. paths.push(path);
  44239. }
  44240. // lathe ribbon
  44241. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44242. return lathe;
  44243. };
  44244. /**
  44245. * Creates a plane mesh.
  44246. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44247. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  44248. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  44249. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  44250. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44251. * 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).
  44252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44254. */
  44255. MeshBuilder.CreatePlane = function (name, options, scene) {
  44256. var plane = new BABYLON.Mesh(name, scene);
  44257. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44258. plane.sideOrientation = options.sideOrientation;
  44259. var vertexData = BABYLON.VertexData.CreatePlane(options);
  44260. vertexData.applyToMesh(plane, options.updatable);
  44261. if (options.sourcePlane) {
  44262. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  44263. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  44264. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  44265. plane.rotate(vectorProduct, product);
  44266. }
  44267. return plane;
  44268. };
  44269. /**
  44270. * Creates a ground mesh.
  44271. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44272. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  44273. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  44274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44275. */
  44276. MeshBuilder.CreateGround = function (name, options, scene) {
  44277. var ground = new BABYLON.GroundMesh(name, scene);
  44278. ground._setReady(false);
  44279. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  44280. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  44281. ground._width = options.width || 1;
  44282. ground._height = options.height || 1;
  44283. ground._maxX = ground._width / 2;
  44284. ground._maxZ = ground._height / 2;
  44285. ground._minX = -ground._maxX;
  44286. ground._minZ = -ground._maxZ;
  44287. var vertexData = BABYLON.VertexData.CreateGround(options);
  44288. vertexData.applyToMesh(ground, options.updatable);
  44289. ground._setReady(true);
  44290. return ground;
  44291. };
  44292. /**
  44293. * Creates a tiled ground mesh.
  44294. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  44295. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  44296. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  44297. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  44298. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  44299. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  44300. * numbers of subdivisions on the ground width and height of each tile.
  44301. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44302. */
  44303. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  44304. var tiledGround = new BABYLON.Mesh(name, scene);
  44305. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  44306. vertexData.applyToMesh(tiledGround, options.updatable);
  44307. return tiledGround;
  44308. };
  44309. /**
  44310. * Creates a ground mesh from a height map.
  44311. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  44312. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  44313. * The parameter `url` sets the URL of the height map image resource.
  44314. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  44315. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  44316. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  44317. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  44318. * 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.
  44319. * 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).
  44320. * This function is passed the newly built mesh :
  44321. * ```javascript
  44322. * function(mesh) { // do things
  44323. * return; }
  44324. * ```
  44325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44326. */
  44327. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  44328. var width = options.width || 10.0;
  44329. var height = options.height || 10.0;
  44330. var subdivisions = options.subdivisions || 1 | 0;
  44331. var minHeight = options.minHeight || 0.0;
  44332. var maxHeight = options.maxHeight || 1.0;
  44333. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  44334. var updatable = options.updatable;
  44335. var onReady = options.onReady;
  44336. var ground = new BABYLON.GroundMesh(name, scene);
  44337. ground._subdivisionsX = subdivisions;
  44338. ground._subdivisionsY = subdivisions;
  44339. ground._width = width;
  44340. ground._height = height;
  44341. ground._maxX = ground._width / 2.0;
  44342. ground._maxZ = ground._height / 2.0;
  44343. ground._minX = -ground._maxX;
  44344. ground._minZ = -ground._maxZ;
  44345. ground._setReady(false);
  44346. var onload = function (img) {
  44347. // Getting height map data
  44348. var canvas = document.createElement("canvas");
  44349. var context = canvas.getContext("2d");
  44350. var bufferWidth = img.width;
  44351. var bufferHeight = img.height;
  44352. canvas.width = bufferWidth;
  44353. canvas.height = bufferHeight;
  44354. context.drawImage(img, 0, 0);
  44355. // Create VertexData from map data
  44356. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  44357. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  44358. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  44359. width: width, height: height,
  44360. subdivisions: subdivisions,
  44361. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  44362. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  44363. });
  44364. vertexData.applyToMesh(ground, updatable);
  44365. ground._setReady(true);
  44366. //execute ready callback, if set
  44367. if (onReady) {
  44368. onReady(ground);
  44369. }
  44370. };
  44371. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  44372. return ground;
  44373. };
  44374. /**
  44375. * Creates a polygon mesh.
  44376. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  44377. * 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.
  44378. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44380. * 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).
  44381. * Remember you can only change the shape positions, not their number when updating a polygon.
  44382. */
  44383. MeshBuilder.CreatePolygon = function (name, options, scene) {
  44384. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44385. var shape = options.shape;
  44386. var holes = options.holes || [];
  44387. var depth = options.depth || 0;
  44388. var contours = [];
  44389. var hole = [];
  44390. for (var i = 0; i < shape.length; i++) {
  44391. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  44392. }
  44393. var epsilon = 0.00000001;
  44394. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  44395. contours.pop();
  44396. }
  44397. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  44398. for (var hNb = 0; hNb < holes.length; hNb++) {
  44399. hole = [];
  44400. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  44401. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  44402. }
  44403. polygonTriangulation.addHole(hole);
  44404. }
  44405. var polygon = polygonTriangulation.build(options.updatable, depth);
  44406. polygon.sideOrientation = options.sideOrientation;
  44407. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  44408. vertexData.applyToMesh(polygon, options.updatable);
  44409. return polygon;
  44410. };
  44411. ;
  44412. /**
  44413. * Creates an extruded polygon mesh, with depth in the Y direction.
  44414. * 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).
  44415. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  44416. */
  44417. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  44418. return MeshBuilder.CreatePolygon(name, options, scene);
  44419. };
  44420. ;
  44421. /**
  44422. * Creates a tube mesh.
  44423. * 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.
  44424. *
  44425. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  44426. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  44427. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  44428. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  44429. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  44430. * 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.
  44431. * It must return a radius value (positive float) :
  44432. * ```javascript
  44433. * var radiusFunction = function(i, distance) {
  44434. * // do things
  44435. * return radius; }
  44436. * ```
  44437. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  44438. * 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
  44439. * 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
  44440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44441. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  44442. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44443. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44445. */
  44446. MeshBuilder.CreateTube = function (name, options, scene) {
  44447. var path = options.path;
  44448. var radius = options.radius || 1.0;
  44449. var tessellation = options.tessellation || 64 | 0;
  44450. var radiusFunction = options.radiusFunction;
  44451. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44452. var invertUV = options.invertUV || false;
  44453. var updatable = options.updatable;
  44454. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44455. var instance = options.instance;
  44456. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  44457. // tube geometry
  44458. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  44459. var tangents = path3D.getTangents();
  44460. var normals = path3D.getNormals();
  44461. var distances = path3D.getDistances();
  44462. var pi2 = Math.PI * 2;
  44463. var step = pi2 / tessellation * arc;
  44464. var returnRadius = function () { return radius; };
  44465. var radiusFunctionFinal = radiusFunction || returnRadius;
  44466. var circlePath;
  44467. var rad;
  44468. var normal;
  44469. var rotated;
  44470. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44471. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44472. for (var i = 0; i < path.length; i++) {
  44473. rad = radiusFunctionFinal(i, distances[i]); // current radius
  44474. circlePath = Array(); // current circle array
  44475. normal = normals[i]; // current normal
  44476. for (var t = 0; t < tessellation; t++) {
  44477. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  44478. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  44479. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  44480. rotated.scaleInPlace(rad).addInPlace(path[i]);
  44481. circlePath[t] = rotated;
  44482. }
  44483. circlePaths[index] = circlePath;
  44484. index++;
  44485. }
  44486. // cap
  44487. var capPath = function (nbPoints, pathIndex) {
  44488. var pointCap = Array();
  44489. for (var i = 0; i < nbPoints; i++) {
  44490. pointCap.push(path[pathIndex]);
  44491. }
  44492. return pointCap;
  44493. };
  44494. switch (cap) {
  44495. case BABYLON.Mesh.NO_CAP:
  44496. break;
  44497. case BABYLON.Mesh.CAP_START:
  44498. circlePaths[0] = capPath(tessellation, 0);
  44499. circlePaths[1] = circlePaths[2].slice(0);
  44500. break;
  44501. case BABYLON.Mesh.CAP_END:
  44502. circlePaths[index] = circlePaths[index - 1].slice(0);
  44503. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44504. break;
  44505. case BABYLON.Mesh.CAP_ALL:
  44506. circlePaths[0] = capPath(tessellation, 0);
  44507. circlePaths[1] = circlePaths[2].slice(0);
  44508. circlePaths[index] = circlePaths[index - 1].slice(0);
  44509. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44510. break;
  44511. default:
  44512. break;
  44513. }
  44514. return circlePaths;
  44515. };
  44516. var path3D;
  44517. var pathArray;
  44518. if (instance) {
  44519. var arc = options.arc || instance.arc;
  44520. path3D = (instance.path3D).update(path);
  44521. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  44522. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  44523. instance.path3D = path3D;
  44524. instance.pathArray = pathArray;
  44525. instance.arc = arc;
  44526. return instance;
  44527. }
  44528. // tube creation
  44529. path3D = new BABYLON.Path3D(path);
  44530. var newPathArray = new Array();
  44531. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44532. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  44533. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44534. tube.pathArray = pathArray;
  44535. tube.path3D = path3D;
  44536. tube.tessellation = tessellation;
  44537. tube.cap = cap;
  44538. tube.arc = options.arc;
  44539. return tube;
  44540. };
  44541. /**
  44542. * Creates a polyhedron mesh.
  44543. *
  44544. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  44545. * 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
  44546. * to choose the wanted type.
  44547. * The parameter `size` (positive float, default 1) sets the polygon size.
  44548. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  44549. * 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`.
  44550. * 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
  44551. * 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)`).
  44552. * 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
  44553. * 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.
  44554. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44555. * 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).
  44556. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44558. */
  44559. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  44560. var polyhedron = new BABYLON.Mesh(name, scene);
  44561. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44562. polyhedron.sideOrientation = options.sideOrientation;
  44563. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  44564. vertexData.applyToMesh(polyhedron, options.updatable);
  44565. return polyhedron;
  44566. };
  44567. /**
  44568. * Creates a decal mesh.
  44569. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  44570. * 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.
  44571. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  44572. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  44573. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  44574. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  44575. */
  44576. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  44577. var indices = sourceMesh.getIndices();
  44578. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44579. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44580. var position = options.position || BABYLON.Vector3.Zero();
  44581. var normal = options.normal || BABYLON.Vector3.Up();
  44582. var size = options.size || BABYLON.Vector3.One();
  44583. var angle = options.angle || 0;
  44584. // Getting correct rotation
  44585. if (!normal) {
  44586. var target = new BABYLON.Vector3(0, 0, 1);
  44587. var camera = sourceMesh.getScene().activeCamera;
  44588. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  44589. normal = camera.globalPosition.subtract(cameraWorldTarget);
  44590. }
  44591. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  44592. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  44593. var pitch = Math.atan2(normal.y, len);
  44594. // Matrix
  44595. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  44596. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  44597. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  44598. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  44599. var vertexData = new BABYLON.VertexData();
  44600. vertexData.indices = [];
  44601. vertexData.positions = [];
  44602. vertexData.normals = [];
  44603. vertexData.uvs = [];
  44604. var currentVertexDataIndex = 0;
  44605. var extractDecalVector3 = function (indexId) {
  44606. var vertexId = indices[indexId];
  44607. var result = new BABYLON.PositionNormalVertex();
  44608. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  44609. // Send vector to decal local world
  44610. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  44611. // Get normal
  44612. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  44613. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  44614. return result;
  44615. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  44616. var clip = function (vertices, axis) {
  44617. if (vertices.length === 0) {
  44618. return vertices;
  44619. }
  44620. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  44621. var clipVertices = function (v0, v1) {
  44622. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  44623. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  44624. };
  44625. var result = new Array();
  44626. for (var index = 0; index < vertices.length; index += 3) {
  44627. var v1Out;
  44628. var v2Out;
  44629. var v3Out;
  44630. var total = 0;
  44631. var nV1, nV2, nV3, nV4;
  44632. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  44633. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  44634. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  44635. v1Out = d1 > 0;
  44636. v2Out = d2 > 0;
  44637. v3Out = d3 > 0;
  44638. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  44639. switch (total) {
  44640. case 0:
  44641. result.push(vertices[index]);
  44642. result.push(vertices[index + 1]);
  44643. result.push(vertices[index + 2]);
  44644. break;
  44645. case 1:
  44646. if (v1Out) {
  44647. nV1 = vertices[index + 1];
  44648. nV2 = vertices[index + 2];
  44649. nV3 = clipVertices(vertices[index], nV1);
  44650. nV4 = clipVertices(vertices[index], nV2);
  44651. }
  44652. if (v2Out) {
  44653. nV1 = vertices[index];
  44654. nV2 = vertices[index + 2];
  44655. nV3 = clipVertices(vertices[index + 1], nV1);
  44656. nV4 = clipVertices(vertices[index + 1], nV2);
  44657. result.push(nV3);
  44658. result.push(nV2.clone());
  44659. result.push(nV1.clone());
  44660. result.push(nV2.clone());
  44661. result.push(nV3.clone());
  44662. result.push(nV4);
  44663. break;
  44664. }
  44665. if (v3Out) {
  44666. nV1 = vertices[index];
  44667. nV2 = vertices[index + 1];
  44668. nV3 = clipVertices(vertices[index + 2], nV1);
  44669. nV4 = clipVertices(vertices[index + 2], nV2);
  44670. }
  44671. result.push(nV1.clone());
  44672. result.push(nV2.clone());
  44673. result.push(nV3);
  44674. result.push(nV4);
  44675. result.push(nV3.clone());
  44676. result.push(nV2.clone());
  44677. break;
  44678. case 2:
  44679. if (!v1Out) {
  44680. nV1 = vertices[index].clone();
  44681. nV2 = clipVertices(nV1, vertices[index + 1]);
  44682. nV3 = clipVertices(nV1, vertices[index + 2]);
  44683. result.push(nV1);
  44684. result.push(nV2);
  44685. result.push(nV3);
  44686. }
  44687. if (!v2Out) {
  44688. nV1 = vertices[index + 1].clone();
  44689. nV2 = clipVertices(nV1, vertices[index + 2]);
  44690. nV3 = clipVertices(nV1, vertices[index]);
  44691. result.push(nV1);
  44692. result.push(nV2);
  44693. result.push(nV3);
  44694. }
  44695. if (!v3Out) {
  44696. nV1 = vertices[index + 2].clone();
  44697. nV2 = clipVertices(nV1, vertices[index]);
  44698. nV3 = clipVertices(nV1, vertices[index + 1]);
  44699. result.push(nV1);
  44700. result.push(nV2);
  44701. result.push(nV3);
  44702. }
  44703. break;
  44704. case 3:
  44705. break;
  44706. }
  44707. }
  44708. return result;
  44709. };
  44710. for (var index = 0; index < indices.length; index += 3) {
  44711. var faceVertices = new Array();
  44712. faceVertices.push(extractDecalVector3(index));
  44713. faceVertices.push(extractDecalVector3(index + 1));
  44714. faceVertices.push(extractDecalVector3(index + 2));
  44715. // Clip
  44716. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  44717. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  44718. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  44719. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  44720. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  44721. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  44722. if (faceVertices.length === 0) {
  44723. continue;
  44724. }
  44725. // Add UVs and get back to world
  44726. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  44727. var vertex = faceVertices[vIndex];
  44728. //TODO check for Int32Array | Uint32Array | Uint16Array
  44729. vertexData.indices.push(currentVertexDataIndex);
  44730. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  44731. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  44732. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  44733. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  44734. currentVertexDataIndex++;
  44735. }
  44736. }
  44737. // Return mesh
  44738. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  44739. vertexData.applyToMesh(decal);
  44740. decal.position = position.clone();
  44741. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  44742. return decal;
  44743. };
  44744. // Privates
  44745. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  44746. // extrusion geometry
  44747. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  44748. var tangents = path3D.getTangents();
  44749. var normals = path3D.getNormals();
  44750. var binormals = path3D.getBinormals();
  44751. var distances = path3D.getDistances();
  44752. var angle = 0;
  44753. var returnScale = function () { return scale; };
  44754. var returnRotation = function () { return rotation; };
  44755. var rotate = custom ? rotateFunction : returnRotation;
  44756. var scl = custom ? scaleFunction : returnScale;
  44757. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44758. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44759. for (var i = 0; i < curve.length; i++) {
  44760. var shapePath = new Array();
  44761. var angleStep = rotate(i, distances[i]);
  44762. var scaleRatio = scl(i, distances[i]);
  44763. for (var p = 0; p < shape.length; p++) {
  44764. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  44765. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  44766. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  44767. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  44768. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  44769. shapePath[p] = rotated;
  44770. }
  44771. shapePaths[index] = shapePath;
  44772. angle += angleStep;
  44773. index++;
  44774. }
  44775. // cap
  44776. var capPath = function (shapePath) {
  44777. var pointCap = Array();
  44778. var barycenter = BABYLON.Vector3.Zero();
  44779. var i;
  44780. for (i = 0; i < shapePath.length; i++) {
  44781. barycenter.addInPlace(shapePath[i]);
  44782. }
  44783. barycenter.scaleInPlace(1.0 / shapePath.length);
  44784. for (i = 0; i < shapePath.length; i++) {
  44785. pointCap.push(barycenter);
  44786. }
  44787. return pointCap;
  44788. };
  44789. switch (cap) {
  44790. case BABYLON.Mesh.NO_CAP:
  44791. break;
  44792. case BABYLON.Mesh.CAP_START:
  44793. shapePaths[0] = capPath(shapePaths[2]);
  44794. shapePaths[1] = shapePaths[2];
  44795. break;
  44796. case BABYLON.Mesh.CAP_END:
  44797. shapePaths[index] = shapePaths[index - 1];
  44798. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44799. break;
  44800. case BABYLON.Mesh.CAP_ALL:
  44801. shapePaths[0] = capPath(shapePaths[2]);
  44802. shapePaths[1] = shapePaths[2];
  44803. shapePaths[index] = shapePaths[index - 1];
  44804. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44805. break;
  44806. default:
  44807. break;
  44808. }
  44809. return shapePaths;
  44810. };
  44811. var path3D;
  44812. var pathArray;
  44813. if (instance) {
  44814. path3D = (instance.path3D).update(curve);
  44815. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  44816. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  44817. return instance;
  44818. }
  44819. // extruded shape creation
  44820. path3D = new BABYLON.Path3D(curve);
  44821. var newShapePaths = new Array();
  44822. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44823. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  44824. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  44825. extrudedGeneric.pathArray = pathArray;
  44826. extrudedGeneric.path3D = path3D;
  44827. extrudedGeneric.cap = cap;
  44828. return extrudedGeneric;
  44829. };
  44830. return MeshBuilder;
  44831. }());
  44832. BABYLON.MeshBuilder = MeshBuilder;
  44833. })(BABYLON || (BABYLON = {}));
  44834. //# sourceMappingURL=babylon.meshBuilder.js.map
  44835. var BABYLON;
  44836. (function (BABYLON) {
  44837. var AudioEngine = (function () {
  44838. function AudioEngine() {
  44839. this._audioContext = null;
  44840. this._audioContextInitialized = false;
  44841. this.canUseWebAudio = false;
  44842. this.WarnedWebAudioUnsupported = false;
  44843. this.unlocked = false;
  44844. this.isMP3supported = false;
  44845. this.isOGGsupported = false;
  44846. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  44847. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  44848. this.canUseWebAudio = true;
  44849. }
  44850. var audioElem = document.createElement('audio');
  44851. try {
  44852. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  44853. this.isMP3supported = true;
  44854. }
  44855. }
  44856. catch (e) {
  44857. // protect error during capability check.
  44858. }
  44859. try {
  44860. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  44861. this.isOGGsupported = true;
  44862. }
  44863. }
  44864. catch (e) {
  44865. // protect error during capability check.
  44866. }
  44867. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  44868. this._unlockiOSaudio();
  44869. }
  44870. else {
  44871. this.unlocked = true;
  44872. }
  44873. }
  44874. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  44875. get: function () {
  44876. if (!this._audioContextInitialized) {
  44877. this._initializeAudioContext();
  44878. }
  44879. return this._audioContext;
  44880. },
  44881. enumerable: true,
  44882. configurable: true
  44883. });
  44884. AudioEngine.prototype._unlockiOSaudio = function () {
  44885. var _this = this;
  44886. var unlockaudio = function () {
  44887. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  44888. var source = _this.audioContext.createBufferSource();
  44889. source.buffer = buffer;
  44890. source.connect(_this.audioContext.destination);
  44891. source.start(0);
  44892. setTimeout(function () {
  44893. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  44894. _this.unlocked = true;
  44895. window.removeEventListener('touchend', unlockaudio, false);
  44896. if (_this.onAudioUnlocked) {
  44897. _this.onAudioUnlocked();
  44898. }
  44899. }
  44900. }, 0);
  44901. };
  44902. window.addEventListener('touchend', unlockaudio, false);
  44903. };
  44904. AudioEngine.prototype._initializeAudioContext = function () {
  44905. try {
  44906. if (this.canUseWebAudio) {
  44907. this._audioContext = new AudioContext();
  44908. // create a global volume gain node
  44909. this.masterGain = this._audioContext.createGain();
  44910. this.masterGain.gain.value = 1;
  44911. this.masterGain.connect(this._audioContext.destination);
  44912. this._audioContextInitialized = true;
  44913. }
  44914. }
  44915. catch (e) {
  44916. this.canUseWebAudio = false;
  44917. BABYLON.Tools.Error("Web Audio: " + e.message);
  44918. }
  44919. };
  44920. AudioEngine.prototype.dispose = function () {
  44921. if (this.canUseWebAudio && this._audioContextInitialized) {
  44922. if (this._connectedAnalyser) {
  44923. this._connectedAnalyser.stopDebugCanvas();
  44924. this._connectedAnalyser.dispose();
  44925. this.masterGain.disconnect();
  44926. this.masterGain.connect(this._audioContext.destination);
  44927. this._connectedAnalyser = null;
  44928. }
  44929. this.masterGain.gain.value = 1;
  44930. }
  44931. this.WarnedWebAudioUnsupported = false;
  44932. };
  44933. AudioEngine.prototype.getGlobalVolume = function () {
  44934. if (this.canUseWebAudio && this._audioContextInitialized) {
  44935. return this.masterGain.gain.value;
  44936. }
  44937. else {
  44938. return -1;
  44939. }
  44940. };
  44941. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  44942. if (this.canUseWebAudio && this._audioContextInitialized) {
  44943. this.masterGain.gain.value = newVolume;
  44944. }
  44945. };
  44946. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  44947. if (this._connectedAnalyser) {
  44948. this._connectedAnalyser.stopDebugCanvas();
  44949. }
  44950. if (this.canUseWebAudio && this._audioContextInitialized) {
  44951. this._connectedAnalyser = analyser;
  44952. this.masterGain.disconnect();
  44953. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  44954. }
  44955. };
  44956. return AudioEngine;
  44957. }());
  44958. BABYLON.AudioEngine = AudioEngine;
  44959. })(BABYLON || (BABYLON = {}));
  44960. //# sourceMappingURL=babylon.audioEngine.js.map
  44961. var BABYLON;
  44962. (function (BABYLON) {
  44963. var Sound = (function () {
  44964. /**
  44965. * Create a sound and attach it to a scene
  44966. * @param name Name of your sound
  44967. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  44968. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  44969. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  44970. */
  44971. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  44972. var _this = this;
  44973. this.autoplay = false;
  44974. this.loop = false;
  44975. this.useCustomAttenuation = false;
  44976. this.spatialSound = false;
  44977. this.refDistance = 1;
  44978. this.rolloffFactor = 1;
  44979. this.maxDistance = 100;
  44980. this.distanceModel = "linear";
  44981. this._panningModel = "equalpower";
  44982. this._playbackRate = 1;
  44983. this._streaming = false;
  44984. this._startTime = 0;
  44985. this._startOffset = 0;
  44986. this._position = BABYLON.Vector3.Zero();
  44987. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  44988. this._volume = 1;
  44989. this._isLoaded = false;
  44990. this._isReadyToPlay = false;
  44991. this.isPlaying = false;
  44992. this.isPaused = false;
  44993. this._isDirectional = false;
  44994. // Used if you'd like to create a directional sound.
  44995. // If not set, the sound will be omnidirectional
  44996. this._coneInnerAngle = 360;
  44997. this._coneOuterAngle = 360;
  44998. this._coneOuterGain = 0;
  44999. this._isOutputConnected = false;
  45000. this._urlType = "Unknown";
  45001. this.name = name;
  45002. this._scene = scene;
  45003. this._readyToPlayCallback = readyToPlayCallback;
  45004. // Default custom attenuation function is a linear attenuation
  45005. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  45006. if (currentDistance < maxDistance) {
  45007. return currentVolume * (1 - currentDistance / maxDistance);
  45008. }
  45009. else {
  45010. return 0;
  45011. }
  45012. };
  45013. if (options) {
  45014. this.autoplay = options.autoplay || false;
  45015. this.loop = options.loop || false;
  45016. // if volume === 0, we need another way to check this option
  45017. if (options.volume !== undefined) {
  45018. this._volume = options.volume;
  45019. }
  45020. this.spatialSound = options.spatialSound || false;
  45021. this.maxDistance = options.maxDistance || 100;
  45022. this.useCustomAttenuation = options.useCustomAttenuation || false;
  45023. this.rolloffFactor = options.rolloffFactor || 1;
  45024. this.refDistance = options.refDistance || 1;
  45025. this.distanceModel = options.distanceModel || "linear";
  45026. this._playbackRate = options.playbackRate || 1;
  45027. this._streaming = options.streaming || false;
  45028. }
  45029. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45030. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  45031. this._soundGain.gain.value = this._volume;
  45032. this._inputAudioNode = this._soundGain;
  45033. this._ouputAudioNode = this._soundGain;
  45034. if (this.spatialSound) {
  45035. this._createSpatialParameters();
  45036. }
  45037. this._scene.mainSoundTrack.AddSound(this);
  45038. var validParameter = true;
  45039. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  45040. if (urlOrArrayBuffer) {
  45041. if (typeof (urlOrArrayBuffer) === "string")
  45042. this._urlType = "String";
  45043. if (Array.isArray(urlOrArrayBuffer))
  45044. this._urlType = "Array";
  45045. if (urlOrArrayBuffer instanceof ArrayBuffer)
  45046. this._urlType = "ArrayBuffer";
  45047. var urls = [];
  45048. var codecSupportedFound = false;
  45049. switch (this._urlType) {
  45050. case "ArrayBuffer":
  45051. if (urlOrArrayBuffer.byteLength > 0) {
  45052. codecSupportedFound = true;
  45053. this._soundLoaded(urlOrArrayBuffer);
  45054. }
  45055. break;
  45056. case "String":
  45057. urls.push(urlOrArrayBuffer);
  45058. case "Array":
  45059. if (urls.length === 0)
  45060. urls = urlOrArrayBuffer;
  45061. // If we found a supported format, we load it immediately and stop the loop
  45062. for (var i = 0; i < urls.length; i++) {
  45063. var url = urls[i];
  45064. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  45065. codecSupportedFound = true;
  45066. }
  45067. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  45068. codecSupportedFound = true;
  45069. }
  45070. if (url.indexOf(".wav", url.length - 4) !== -1) {
  45071. codecSupportedFound = true;
  45072. }
  45073. if (url.indexOf("blob:") !== -1) {
  45074. codecSupportedFound = true;
  45075. }
  45076. if (codecSupportedFound) {
  45077. // Loading sound using XHR2
  45078. if (!this._streaming) {
  45079. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  45080. }
  45081. else {
  45082. this._htmlAudioElement = new Audio(url);
  45083. this._htmlAudioElement.controls = false;
  45084. this._htmlAudioElement.loop = this.loop;
  45085. this._htmlAudioElement.crossOrigin = "anonymous";
  45086. this._htmlAudioElement.preload = "auto";
  45087. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  45088. _this._isReadyToPlay = true;
  45089. if (_this.autoplay) {
  45090. _this.play();
  45091. }
  45092. if (_this._readyToPlayCallback) {
  45093. _this._readyToPlayCallback();
  45094. }
  45095. });
  45096. document.body.appendChild(this._htmlAudioElement);
  45097. }
  45098. break;
  45099. }
  45100. }
  45101. break;
  45102. default:
  45103. validParameter = false;
  45104. break;
  45105. }
  45106. if (!validParameter) {
  45107. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  45108. }
  45109. else {
  45110. if (!codecSupportedFound) {
  45111. this._isReadyToPlay = true;
  45112. // Simulating a ready to play event to avoid breaking code path
  45113. if (this._readyToPlayCallback) {
  45114. window.setTimeout(function () {
  45115. _this._readyToPlayCallback();
  45116. }, 1000);
  45117. }
  45118. }
  45119. }
  45120. }
  45121. }
  45122. else {
  45123. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  45124. this._scene.mainSoundTrack.AddSound(this);
  45125. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  45126. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  45127. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  45128. }
  45129. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  45130. if (this._readyToPlayCallback) {
  45131. window.setTimeout(function () {
  45132. _this._readyToPlayCallback();
  45133. }, 1000);
  45134. }
  45135. }
  45136. }
  45137. Sound.prototype.dispose = function () {
  45138. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  45139. if (this.isPlaying) {
  45140. this.stop();
  45141. }
  45142. this._isReadyToPlay = false;
  45143. if (this.soundTrackId === -1) {
  45144. this._scene.mainSoundTrack.RemoveSound(this);
  45145. }
  45146. else {
  45147. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  45148. }
  45149. if (this._soundGain) {
  45150. this._soundGain.disconnect();
  45151. this._soundGain = null;
  45152. }
  45153. if (this._soundPanner) {
  45154. this._soundPanner.disconnect();
  45155. this._soundPanner = null;
  45156. }
  45157. if (this._soundSource) {
  45158. this._soundSource.disconnect();
  45159. this._soundSource = null;
  45160. }
  45161. this._audioBuffer = null;
  45162. if (this._htmlAudioElement) {
  45163. this._htmlAudioElement.pause();
  45164. this._htmlAudioElement.src = "";
  45165. document.body.removeChild(this._htmlAudioElement);
  45166. }
  45167. if (this._connectedMesh) {
  45168. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45169. this._connectedMesh = null;
  45170. }
  45171. }
  45172. };
  45173. Sound.prototype.isReady = function () {
  45174. return this._isReadyToPlay;
  45175. };
  45176. Sound.prototype._soundLoaded = function (audioData) {
  45177. var _this = this;
  45178. this._isLoaded = true;
  45179. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  45180. _this._audioBuffer = buffer;
  45181. _this._isReadyToPlay = true;
  45182. if (_this.autoplay) {
  45183. _this.play();
  45184. }
  45185. if (_this._readyToPlayCallback) {
  45186. _this._readyToPlayCallback();
  45187. }
  45188. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  45189. };
  45190. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  45191. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45192. this._audioBuffer = audioBuffer;
  45193. this._isReadyToPlay = true;
  45194. }
  45195. };
  45196. Sound.prototype.updateOptions = function (options) {
  45197. if (options) {
  45198. this.loop = options.loop || this.loop;
  45199. this.maxDistance = options.maxDistance || this.maxDistance;
  45200. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  45201. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  45202. this.refDistance = options.refDistance || this.refDistance;
  45203. this.distanceModel = options.distanceModel || this.distanceModel;
  45204. this._playbackRate = options.playbackRate || this._playbackRate;
  45205. this._updateSpatialParameters();
  45206. if (this.isPlaying) {
  45207. if (this._streaming) {
  45208. this._htmlAudioElement.playbackRate = this._playbackRate;
  45209. }
  45210. else {
  45211. this._soundSource.playbackRate.value = this._playbackRate;
  45212. }
  45213. }
  45214. }
  45215. };
  45216. Sound.prototype._createSpatialParameters = function () {
  45217. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45218. if (this._scene.headphone) {
  45219. this._panningModel = "HRTF";
  45220. }
  45221. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  45222. this._updateSpatialParameters();
  45223. this._soundPanner.connect(this._ouputAudioNode);
  45224. this._inputAudioNode = this._soundPanner;
  45225. }
  45226. };
  45227. Sound.prototype._updateSpatialParameters = function () {
  45228. if (this.spatialSound) {
  45229. if (this.useCustomAttenuation) {
  45230. // Tricks to disable in a way embedded Web Audio attenuation
  45231. this._soundPanner.distanceModel = "linear";
  45232. this._soundPanner.maxDistance = Number.MAX_VALUE;
  45233. this._soundPanner.refDistance = 1;
  45234. this._soundPanner.rolloffFactor = 1;
  45235. this._soundPanner.panningModel = this._panningModel;
  45236. }
  45237. else {
  45238. this._soundPanner.distanceModel = this.distanceModel;
  45239. this._soundPanner.maxDistance = this.maxDistance;
  45240. this._soundPanner.refDistance = this.refDistance;
  45241. this._soundPanner.rolloffFactor = this.rolloffFactor;
  45242. this._soundPanner.panningModel = this._panningModel;
  45243. }
  45244. }
  45245. };
  45246. Sound.prototype.switchPanningModelToHRTF = function () {
  45247. this._panningModel = "HRTF";
  45248. this._switchPanningModel();
  45249. };
  45250. Sound.prototype.switchPanningModelToEqualPower = function () {
  45251. this._panningModel = "equalpower";
  45252. this._switchPanningModel();
  45253. };
  45254. Sound.prototype._switchPanningModel = function () {
  45255. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45256. this._soundPanner.panningModel = this._panningModel;
  45257. }
  45258. };
  45259. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  45260. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45261. if (this._isOutputConnected) {
  45262. this._ouputAudioNode.disconnect();
  45263. }
  45264. this._ouputAudioNode.connect(soundTrackAudioNode);
  45265. this._isOutputConnected = true;
  45266. }
  45267. };
  45268. /**
  45269. * Transform this sound into a directional source
  45270. * @param coneInnerAngle Size of the inner cone in degree
  45271. * @param coneOuterAngle Size of the outer cone in degree
  45272. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  45273. */
  45274. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  45275. if (coneOuterAngle < coneInnerAngle) {
  45276. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  45277. return;
  45278. }
  45279. this._coneInnerAngle = coneInnerAngle;
  45280. this._coneOuterAngle = coneOuterAngle;
  45281. this._coneOuterGain = coneOuterGain;
  45282. this._isDirectional = true;
  45283. if (this.isPlaying && this.loop) {
  45284. this.stop();
  45285. this.play();
  45286. }
  45287. };
  45288. Sound.prototype.setPosition = function (newPosition) {
  45289. this._position = newPosition;
  45290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45291. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45292. }
  45293. };
  45294. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  45295. this._localDirection = newLocalDirection;
  45296. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  45297. this._updateDirection();
  45298. }
  45299. };
  45300. Sound.prototype._updateDirection = function () {
  45301. var mat = this._connectedMesh.getWorldMatrix();
  45302. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  45303. direction.normalize();
  45304. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  45305. };
  45306. Sound.prototype.updateDistanceFromListener = function () {
  45307. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  45308. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  45309. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  45310. }
  45311. };
  45312. Sound.prototype.setAttenuationFunction = function (callback) {
  45313. this._customAttenuationFunction = callback;
  45314. };
  45315. /**
  45316. * Play the sound
  45317. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  45318. * @param offset (optional) Start the sound setting it at a specific time
  45319. */
  45320. Sound.prototype.play = function (time, offset) {
  45321. var _this = this;
  45322. if (this._isReadyToPlay && this._scene.audioEnabled) {
  45323. try {
  45324. if (this._startOffset < 0) {
  45325. time = -this._startOffset;
  45326. this._startOffset = 0;
  45327. }
  45328. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45329. if (!this._soundSource || !this._streamingSource) {
  45330. if (this.spatialSound) {
  45331. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45332. if (this._isDirectional) {
  45333. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  45334. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  45335. this._soundPanner.coneOuterGain = this._coneOuterGain;
  45336. if (this._connectedMesh) {
  45337. this._updateDirection();
  45338. }
  45339. else {
  45340. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  45341. }
  45342. }
  45343. }
  45344. }
  45345. if (this._streaming) {
  45346. if (!this._streamingSource) {
  45347. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  45348. this._htmlAudioElement.onended = function () { _this._onended(); };
  45349. this._htmlAudioElement.playbackRate = this._playbackRate;
  45350. }
  45351. this._streamingSource.disconnect();
  45352. this._streamingSource.connect(this._inputAudioNode);
  45353. this._htmlAudioElement.play();
  45354. }
  45355. else {
  45356. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  45357. this._soundSource.buffer = this._audioBuffer;
  45358. this._soundSource.connect(this._inputAudioNode);
  45359. this._soundSource.loop = this.loop;
  45360. this._soundSource.playbackRate.value = this._playbackRate;
  45361. this._soundSource.onended = function () { _this._onended(); };
  45362. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  45363. }
  45364. this._startTime = startTime;
  45365. this.isPlaying = true;
  45366. this.isPaused = false;
  45367. }
  45368. catch (ex) {
  45369. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  45370. }
  45371. }
  45372. };
  45373. Sound.prototype._onended = function () {
  45374. this.isPlaying = false;
  45375. if (this.onended) {
  45376. this.onended();
  45377. }
  45378. };
  45379. /**
  45380. * Stop the sound
  45381. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  45382. */
  45383. Sound.prototype.stop = function (time) {
  45384. if (this.isPlaying) {
  45385. if (this._streaming) {
  45386. this._htmlAudioElement.pause();
  45387. // Test needed for Firefox or it will generate an Invalid State Error
  45388. if (this._htmlAudioElement.currentTime > 0) {
  45389. this._htmlAudioElement.currentTime = 0;
  45390. }
  45391. }
  45392. else {
  45393. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45394. this._soundSource.stop(stopTime);
  45395. this._soundSource.onended = null;
  45396. if (!this.isPaused) {
  45397. this._startOffset = 0;
  45398. }
  45399. }
  45400. this.isPlaying = false;
  45401. }
  45402. };
  45403. Sound.prototype.pause = function () {
  45404. if (this.isPlaying) {
  45405. this.isPaused = true;
  45406. if (this._streaming) {
  45407. this._htmlAudioElement.pause();
  45408. }
  45409. else {
  45410. this.stop(0);
  45411. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  45412. }
  45413. }
  45414. };
  45415. Sound.prototype.setVolume = function (newVolume, time) {
  45416. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45417. if (time) {
  45418. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  45419. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  45420. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  45421. }
  45422. else {
  45423. this._soundGain.gain.value = newVolume;
  45424. }
  45425. }
  45426. this._volume = newVolume;
  45427. };
  45428. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  45429. this._playbackRate = newPlaybackRate;
  45430. if (this.isPlaying) {
  45431. if (this._streaming) {
  45432. this._htmlAudioElement.playbackRate = this._playbackRate;
  45433. }
  45434. else {
  45435. this._soundSource.playbackRate.value = this._playbackRate;
  45436. }
  45437. }
  45438. };
  45439. Sound.prototype.getVolume = function () {
  45440. return this._volume;
  45441. };
  45442. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  45443. var _this = this;
  45444. if (this._connectedMesh) {
  45445. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45446. this._registerFunc = null;
  45447. }
  45448. this._connectedMesh = meshToConnectTo;
  45449. if (!this.spatialSound) {
  45450. this.spatialSound = true;
  45451. this._createSpatialParameters();
  45452. if (this.isPlaying && this.loop) {
  45453. this.stop();
  45454. this.play();
  45455. }
  45456. }
  45457. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  45458. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  45459. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  45460. };
  45461. Sound.prototype.detachFromMesh = function () {
  45462. if (this._connectedMesh) {
  45463. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45464. this._registerFunc = null;
  45465. this._connectedMesh = null;
  45466. }
  45467. };
  45468. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  45469. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  45470. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  45471. this._updateDirection();
  45472. }
  45473. };
  45474. Sound.prototype.clone = function () {
  45475. var _this = this;
  45476. if (!this._streaming) {
  45477. var setBufferAndRun = function () {
  45478. if (_this._isReadyToPlay) {
  45479. clonedSound._audioBuffer = _this.getAudioBuffer();
  45480. clonedSound._isReadyToPlay = true;
  45481. if (clonedSound.autoplay) {
  45482. clonedSound.play();
  45483. }
  45484. }
  45485. else {
  45486. window.setTimeout(setBufferAndRun, 300);
  45487. }
  45488. };
  45489. var currentOptions = {
  45490. autoplay: this.autoplay, loop: this.loop,
  45491. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  45492. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  45493. refDistance: this.refDistance, distanceModel: this.distanceModel
  45494. };
  45495. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  45496. if (this.useCustomAttenuation) {
  45497. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  45498. }
  45499. clonedSound.setPosition(this._position);
  45500. clonedSound.setPlaybackRate(this._playbackRate);
  45501. setBufferAndRun();
  45502. return clonedSound;
  45503. }
  45504. else {
  45505. return null;
  45506. }
  45507. };
  45508. Sound.prototype.getAudioBuffer = function () {
  45509. return this._audioBuffer;
  45510. };
  45511. Sound.prototype.serialize = function () {
  45512. var serializationObject = {
  45513. name: this.name,
  45514. url: this.name,
  45515. autoplay: this.autoplay,
  45516. loop: this.loop,
  45517. volume: this._volume,
  45518. spatialSound: this.spatialSound,
  45519. maxDistance: this.maxDistance,
  45520. rolloffFactor: this.rolloffFactor,
  45521. refDistance: this.refDistance,
  45522. distanceModel: this.distanceModel,
  45523. playbackRate: this._playbackRate,
  45524. panningModel: this._panningModel,
  45525. soundTrackId: this.soundTrackId
  45526. };
  45527. if (this.spatialSound) {
  45528. if (this._connectedMesh)
  45529. serializationObject.connectedMeshId = this._connectedMesh.id;
  45530. serializationObject.position = this._position.asArray();
  45531. serializationObject.refDistance = this.refDistance;
  45532. serializationObject.distanceModel = this.distanceModel;
  45533. serializationObject.isDirectional = this._isDirectional;
  45534. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  45535. serializationObject.coneInnerAngle = this._coneInnerAngle;
  45536. serializationObject.coneOuterAngle = this._coneOuterAngle;
  45537. serializationObject.coneOuterGain = this._coneOuterGain;
  45538. }
  45539. return serializationObject;
  45540. };
  45541. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  45542. var soundName = parsedSound.name;
  45543. var soundUrl;
  45544. if (parsedSound.url) {
  45545. soundUrl = rootUrl + parsedSound.url;
  45546. }
  45547. else {
  45548. soundUrl = rootUrl + soundName;
  45549. }
  45550. var options = {
  45551. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  45552. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  45553. rolloffFactor: parsedSound.rolloffFactor,
  45554. refDistance: parsedSound.refDistance,
  45555. distanceModel: parsedSound.distanceModel,
  45556. playbackRate: parsedSound.playbackRate
  45557. };
  45558. var newSound;
  45559. if (!sourceSound) {
  45560. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  45561. scene._addPendingData(newSound);
  45562. }
  45563. else {
  45564. var setBufferAndRun = function () {
  45565. if (sourceSound._isReadyToPlay) {
  45566. newSound._audioBuffer = sourceSound.getAudioBuffer();
  45567. newSound._isReadyToPlay = true;
  45568. if (newSound.autoplay) {
  45569. newSound.play();
  45570. }
  45571. }
  45572. else {
  45573. window.setTimeout(setBufferAndRun, 300);
  45574. }
  45575. };
  45576. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  45577. setBufferAndRun();
  45578. }
  45579. if (parsedSound.position) {
  45580. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  45581. newSound.setPosition(soundPosition);
  45582. }
  45583. if (parsedSound.isDirectional) {
  45584. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  45585. if (parsedSound.localDirectionToMesh) {
  45586. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  45587. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  45588. }
  45589. }
  45590. if (parsedSound.connectedMeshId) {
  45591. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  45592. if (connectedMesh) {
  45593. newSound.attachToMesh(connectedMesh);
  45594. }
  45595. }
  45596. return newSound;
  45597. };
  45598. return Sound;
  45599. }());
  45600. BABYLON.Sound = Sound;
  45601. })(BABYLON || (BABYLON = {}));
  45602. //# sourceMappingURL=babylon.sound.js.map
  45603. var BABYLON;
  45604. (function (BABYLON) {
  45605. var SoundTrack = (function () {
  45606. function SoundTrack(scene, options) {
  45607. this.id = -1;
  45608. this._isMainTrack = false;
  45609. this._isInitialized = false;
  45610. this._scene = scene;
  45611. this.soundCollection = new Array();
  45612. this._options = options;
  45613. if (!this._isMainTrack) {
  45614. this._scene.soundTracks.push(this);
  45615. this.id = this._scene.soundTracks.length - 1;
  45616. }
  45617. }
  45618. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  45619. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45620. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  45621. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  45622. if (this._options) {
  45623. if (this._options.volume) {
  45624. this._outputAudioNode.gain.value = this._options.volume;
  45625. }
  45626. if (this._options.mainTrack) {
  45627. this._isMainTrack = this._options.mainTrack;
  45628. }
  45629. }
  45630. this._isInitialized = true;
  45631. }
  45632. };
  45633. SoundTrack.prototype.dispose = function () {
  45634. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45635. if (this._connectedAnalyser) {
  45636. this._connectedAnalyser.stopDebugCanvas();
  45637. }
  45638. while (this.soundCollection.length) {
  45639. this.soundCollection[0].dispose();
  45640. }
  45641. if (this._outputAudioNode) {
  45642. this._outputAudioNode.disconnect();
  45643. }
  45644. this._outputAudioNode = null;
  45645. }
  45646. };
  45647. SoundTrack.prototype.AddSound = function (sound) {
  45648. if (!this._isInitialized) {
  45649. this._initializeSoundTrackAudioGraph();
  45650. }
  45651. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45652. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  45653. }
  45654. if (sound.soundTrackId) {
  45655. if (sound.soundTrackId === -1) {
  45656. this._scene.mainSoundTrack.RemoveSound(sound);
  45657. }
  45658. else {
  45659. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  45660. }
  45661. }
  45662. this.soundCollection.push(sound);
  45663. sound.soundTrackId = this.id;
  45664. };
  45665. SoundTrack.prototype.RemoveSound = function (sound) {
  45666. var index = this.soundCollection.indexOf(sound);
  45667. if (index !== -1) {
  45668. this.soundCollection.splice(index, 1);
  45669. }
  45670. };
  45671. SoundTrack.prototype.setVolume = function (newVolume) {
  45672. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45673. this._outputAudioNode.gain.value = newVolume;
  45674. }
  45675. };
  45676. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  45677. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45678. for (var i = 0; i < this.soundCollection.length; i++) {
  45679. this.soundCollection[i].switchPanningModelToHRTF();
  45680. }
  45681. }
  45682. };
  45683. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  45684. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45685. for (var i = 0; i < this.soundCollection.length; i++) {
  45686. this.soundCollection[i].switchPanningModelToEqualPower();
  45687. }
  45688. }
  45689. };
  45690. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  45691. if (this._connectedAnalyser) {
  45692. this._connectedAnalyser.stopDebugCanvas();
  45693. }
  45694. this._connectedAnalyser = analyser;
  45695. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45696. this._outputAudioNode.disconnect();
  45697. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  45698. }
  45699. };
  45700. return SoundTrack;
  45701. }());
  45702. BABYLON.SoundTrack = SoundTrack;
  45703. })(BABYLON || (BABYLON = {}));
  45704. //# sourceMappingURL=babylon.soundtrack.js.map
  45705. var BABYLON;
  45706. (function (BABYLON) {
  45707. var Analyser = (function () {
  45708. function Analyser(scene) {
  45709. this.SMOOTHING = 0.75;
  45710. this.FFT_SIZE = 512;
  45711. this.BARGRAPHAMPLITUDE = 256;
  45712. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45713. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45714. this._scene = scene;
  45715. this._audioEngine = BABYLON.Engine.audioEngine;
  45716. if (this._audioEngine.canUseWebAudio) {
  45717. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45718. this._webAudioAnalyser.minDecibels = -140;
  45719. this._webAudioAnalyser.maxDecibels = 0;
  45720. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45721. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45722. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45723. }
  45724. }
  45725. Analyser.prototype.getFrequencyBinCount = function () {
  45726. if (this._audioEngine.canUseWebAudio) {
  45727. return this._webAudioAnalyser.frequencyBinCount;
  45728. }
  45729. else {
  45730. return 0;
  45731. }
  45732. };
  45733. Analyser.prototype.getByteFrequencyData = function () {
  45734. if (this._audioEngine.canUseWebAudio) {
  45735. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45736. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45737. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45738. }
  45739. return this._byteFreqs;
  45740. };
  45741. Analyser.prototype.getByteTimeDomainData = function () {
  45742. if (this._audioEngine.canUseWebAudio) {
  45743. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45744. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45745. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45746. }
  45747. return this._byteTime;
  45748. };
  45749. Analyser.prototype.getFloatFrequencyData = function () {
  45750. if (this._audioEngine.canUseWebAudio) {
  45751. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45752. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45753. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45754. }
  45755. return this._floatFreqs;
  45756. };
  45757. Analyser.prototype.drawDebugCanvas = function () {
  45758. var _this = this;
  45759. if (this._audioEngine.canUseWebAudio) {
  45760. if (!this._debugCanvas) {
  45761. this._debugCanvas = document.createElement("canvas");
  45762. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45763. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45764. this._debugCanvas.style.position = "absolute";
  45765. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45766. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45767. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45768. document.body.appendChild(this._debugCanvas);
  45769. this._registerFunc = function () {
  45770. _this.drawDebugCanvas();
  45771. };
  45772. this._scene.registerBeforeRender(this._registerFunc);
  45773. }
  45774. if (this._registerFunc) {
  45775. var workingArray = this.getByteFrequencyData();
  45776. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45777. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45778. // Draw the frequency domain chart.
  45779. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45780. var value = workingArray[i];
  45781. var percent = value / this.BARGRAPHAMPLITUDE;
  45782. var height = this.DEBUGCANVASSIZE.height * percent;
  45783. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45784. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45785. var hue = i / this.getFrequencyBinCount() * 360;
  45786. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45787. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45788. }
  45789. }
  45790. }
  45791. };
  45792. Analyser.prototype.stopDebugCanvas = function () {
  45793. if (this._debugCanvas) {
  45794. this._scene.unregisterBeforeRender(this._registerFunc);
  45795. this._registerFunc = null;
  45796. document.body.removeChild(this._debugCanvas);
  45797. this._debugCanvas = null;
  45798. this._debugCanvasContext = null;
  45799. }
  45800. };
  45801. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45802. if (this._audioEngine.canUseWebAudio) {
  45803. inputAudioNode.connect(this._webAudioAnalyser);
  45804. this._webAudioAnalyser.connect(outputAudioNode);
  45805. }
  45806. };
  45807. Analyser.prototype.dispose = function () {
  45808. if (this._audioEngine.canUseWebAudio) {
  45809. this._webAudioAnalyser.disconnect();
  45810. }
  45811. };
  45812. return Analyser;
  45813. }());
  45814. BABYLON.Analyser = Analyser;
  45815. })(BABYLON || (BABYLON = {}));
  45816. //# sourceMappingURL=babylon.analyser.js.map
  45817. var BABYLON;
  45818. (function (BABYLON) {
  45819. var CubeTexture = (function (_super) {
  45820. __extends(CubeTexture, _super);
  45821. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  45822. if (onLoad === void 0) { onLoad = null; }
  45823. if (onError === void 0) { onError = null; }
  45824. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45825. if (prefiltered === void 0) { prefiltered = false; }
  45826. if (forcedExtension === void 0) { forcedExtension = null; }
  45827. var _this = _super.call(this, scene) || this;
  45828. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  45829. _this.name = rootUrl;
  45830. _this.url = rootUrl;
  45831. _this._noMipmap = noMipmap;
  45832. _this.hasAlpha = false;
  45833. _this._format = format;
  45834. _this._prefiltered = prefiltered;
  45835. _this.isCube = true;
  45836. _this._textureMatrix = BABYLON.Matrix.Identity();
  45837. if (prefiltered) {
  45838. _this.gammaSpace = false;
  45839. }
  45840. if (!rootUrl && !files) {
  45841. return _this;
  45842. }
  45843. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  45844. if (!files) {
  45845. if (!extensions) {
  45846. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  45847. }
  45848. files = [];
  45849. for (var index = 0; index < extensions.length; index++) {
  45850. files.push(rootUrl + extensions[index]);
  45851. }
  45852. _this._extensions = extensions;
  45853. }
  45854. _this._files = files;
  45855. if (!_this._texture) {
  45856. if (!scene.useDelayedTextureLoading) {
  45857. if (prefiltered) {
  45858. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  45859. }
  45860. else {
  45861. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  45862. }
  45863. }
  45864. else {
  45865. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  45866. }
  45867. }
  45868. else if (onLoad) {
  45869. if (_this._texture.isReady) {
  45870. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  45871. }
  45872. else {
  45873. _this._texture.onLoadedObservable.add(onLoad);
  45874. }
  45875. }
  45876. return _this;
  45877. }
  45878. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  45879. return new CubeTexture("", scene, null, noMipmap, files);
  45880. };
  45881. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  45882. if (forcedExtension === void 0) { forcedExtension = null; }
  45883. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  45884. };
  45885. // Methods
  45886. CubeTexture.prototype.delayLoad = function () {
  45887. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  45888. return;
  45889. }
  45890. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  45891. this._texture = this._getFromCache(this.url, this._noMipmap);
  45892. if (!this._texture) {
  45893. if (this._prefiltered) {
  45894. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  45895. }
  45896. else {
  45897. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  45898. }
  45899. }
  45900. };
  45901. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  45902. return this._textureMatrix;
  45903. };
  45904. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  45905. this._textureMatrix = value;
  45906. };
  45907. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  45908. var texture = BABYLON.SerializationHelper.Parse(function () {
  45909. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  45910. }, parsedTexture, scene);
  45911. // Animations
  45912. if (parsedTexture.animations) {
  45913. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  45914. var parsedAnimation = parsedTexture.animations[animationIndex];
  45915. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45916. }
  45917. }
  45918. return texture;
  45919. };
  45920. CubeTexture.prototype.clone = function () {
  45921. var _this = this;
  45922. return BABYLON.SerializationHelper.Clone(function () {
  45923. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  45924. }, this);
  45925. };
  45926. return CubeTexture;
  45927. }(BABYLON.BaseTexture));
  45928. BABYLON.CubeTexture = CubeTexture;
  45929. })(BABYLON || (BABYLON = {}));
  45930. //# sourceMappingURL=babylon.cubeTexture.js.map
  45931. var BABYLON;
  45932. (function (BABYLON) {
  45933. var RenderTargetTexture = (function (_super) {
  45934. __extends(RenderTargetTexture, _super);
  45935. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  45936. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  45937. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45938. if (isCube === void 0) { isCube = false; }
  45939. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45940. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45941. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  45942. if (isMulti === void 0) { isMulti = false; }
  45943. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  45944. _this.isCube = isCube;
  45945. /**
  45946. * Use this list to define the list of mesh you want to render.
  45947. */
  45948. _this.renderList = new Array();
  45949. _this.renderParticles = true;
  45950. _this.renderSprites = false;
  45951. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  45952. _this.ignoreCameraViewport = false;
  45953. // Events
  45954. /**
  45955. * An event triggered when the texture is unbind.
  45956. * @type {BABYLON.Observable}
  45957. */
  45958. _this.onBeforeBindObservable = new BABYLON.Observable();
  45959. /**
  45960. * An event triggered when the texture is unbind.
  45961. * @type {BABYLON.Observable}
  45962. */
  45963. _this.onAfterUnbindObservable = new BABYLON.Observable();
  45964. /**
  45965. * An event triggered before rendering the texture
  45966. * @type {BABYLON.Observable}
  45967. */
  45968. _this.onBeforeRenderObservable = new BABYLON.Observable();
  45969. /**
  45970. * An event triggered after rendering the texture
  45971. * @type {BABYLON.Observable}
  45972. */
  45973. _this.onAfterRenderObservable = new BABYLON.Observable();
  45974. /**
  45975. * An event triggered after the texture clear
  45976. * @type {BABYLON.Observable}
  45977. */
  45978. _this.onClearObservable = new BABYLON.Observable();
  45979. _this._currentRefreshId = -1;
  45980. _this._refreshRate = 1;
  45981. _this._samples = 1;
  45982. scene = _this.getScene();
  45983. _this.name = name;
  45984. _this.isRenderTarget = true;
  45985. _this._size = size;
  45986. _this._generateMipMaps = generateMipMaps;
  45987. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  45988. // Rendering groups
  45989. _this._renderingManager = new BABYLON.RenderingManager(scene);
  45990. if (isMulti) {
  45991. return _this;
  45992. }
  45993. _this._renderTargetOptions = {
  45994. generateMipMaps: generateMipMaps,
  45995. type: type,
  45996. samplingMode: samplingMode,
  45997. generateDepthBuffer: generateDepthBuffer,
  45998. generateStencilBuffer: generateStencilBuffer
  45999. };
  46000. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  46001. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46002. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46003. }
  46004. if (isCube) {
  46005. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  46006. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  46007. _this._textureMatrix = BABYLON.Matrix.Identity();
  46008. }
  46009. else {
  46010. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  46011. }
  46012. return _this;
  46013. }
  46014. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  46015. get: function () {
  46016. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  46017. },
  46018. enumerable: true,
  46019. configurable: true
  46020. });
  46021. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  46022. get: function () {
  46023. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  46024. },
  46025. enumerable: true,
  46026. configurable: true
  46027. });
  46028. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  46029. get: function () {
  46030. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  46031. },
  46032. enumerable: true,
  46033. configurable: true
  46034. });
  46035. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  46036. set: function (callback) {
  46037. if (this._onAfterUnbindObserver) {
  46038. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  46039. }
  46040. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  46041. },
  46042. enumerable: true,
  46043. configurable: true
  46044. });
  46045. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  46046. set: function (callback) {
  46047. if (this._onBeforeRenderObserver) {
  46048. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  46049. }
  46050. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  46051. },
  46052. enumerable: true,
  46053. configurable: true
  46054. });
  46055. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  46056. set: function (callback) {
  46057. if (this._onAfterRenderObserver) {
  46058. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  46059. }
  46060. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  46061. },
  46062. enumerable: true,
  46063. configurable: true
  46064. });
  46065. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  46066. set: function (callback) {
  46067. if (this._onClearObserver) {
  46068. this.onClearObservable.remove(this._onClearObserver);
  46069. }
  46070. this._onClearObserver = this.onClearObservable.add(callback);
  46071. },
  46072. enumerable: true,
  46073. configurable: true
  46074. });
  46075. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  46076. get: function () {
  46077. return this._renderTargetOptions;
  46078. },
  46079. enumerable: true,
  46080. configurable: true
  46081. });
  46082. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  46083. get: function () {
  46084. return this._samples;
  46085. },
  46086. set: function (value) {
  46087. if (this._samples === value) {
  46088. return;
  46089. }
  46090. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  46091. },
  46092. enumerable: true,
  46093. configurable: true
  46094. });
  46095. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  46096. this._currentRefreshId = -1;
  46097. };
  46098. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  46099. get: function () {
  46100. return this._refreshRate;
  46101. },
  46102. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  46103. set: function (value) {
  46104. this._refreshRate = value;
  46105. this.resetRefreshCounter();
  46106. },
  46107. enumerable: true,
  46108. configurable: true
  46109. });
  46110. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  46111. if (!this._postProcessManager) {
  46112. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  46113. this._postProcesses = new Array();
  46114. }
  46115. this._postProcesses.push(postProcess);
  46116. this._postProcesses[0].autoClear = false;
  46117. };
  46118. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  46119. if (!this._postProcesses) {
  46120. return;
  46121. }
  46122. if (dispose) {
  46123. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  46124. var postProcess = _a[_i];
  46125. postProcess.dispose();
  46126. postProcess = null;
  46127. }
  46128. }
  46129. this._postProcesses = [];
  46130. };
  46131. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  46132. if (!this._postProcesses) {
  46133. return;
  46134. }
  46135. var index = this._postProcesses.indexOf(postProcess);
  46136. if (index === -1) {
  46137. return;
  46138. }
  46139. this._postProcesses.splice(index, 1);
  46140. if (this._postProcesses.length > 0) {
  46141. this._postProcesses[0].autoClear = false;
  46142. }
  46143. };
  46144. RenderTargetTexture.prototype._shouldRender = function () {
  46145. if (this._currentRefreshId === -1) {
  46146. this._currentRefreshId = 1;
  46147. return true;
  46148. }
  46149. if (this.refreshRate === this._currentRefreshId) {
  46150. this._currentRefreshId = 1;
  46151. return true;
  46152. }
  46153. this._currentRefreshId++;
  46154. return false;
  46155. };
  46156. RenderTargetTexture.prototype.getRenderSize = function () {
  46157. return this._size;
  46158. };
  46159. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  46160. get: function () {
  46161. return true;
  46162. },
  46163. enumerable: true,
  46164. configurable: true
  46165. });
  46166. RenderTargetTexture.prototype.scale = function (ratio) {
  46167. var newSize = this._size * ratio;
  46168. this.resize(newSize);
  46169. };
  46170. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  46171. if (this.isCube) {
  46172. return this._textureMatrix;
  46173. }
  46174. return _super.prototype.getReflectionTextureMatrix.call(this);
  46175. };
  46176. RenderTargetTexture.prototype.resize = function (size) {
  46177. this.releaseInternalTexture();
  46178. if (this.isCube) {
  46179. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  46180. }
  46181. else {
  46182. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  46183. }
  46184. };
  46185. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  46186. var scene = this.getScene();
  46187. var engine = scene.getEngine();
  46188. if (this.useCameraPostProcesses !== undefined) {
  46189. useCameraPostProcess = this.useCameraPostProcesses;
  46190. }
  46191. if (this._waitingRenderList) {
  46192. this.renderList = [];
  46193. for (var index = 0; index < this._waitingRenderList.length; index++) {
  46194. var id = this._waitingRenderList[index];
  46195. this.renderList.push(scene.getMeshByID(id));
  46196. }
  46197. delete this._waitingRenderList;
  46198. }
  46199. // Is predicate defined?
  46200. if (this.renderListPredicate) {
  46201. this.renderList.splice(0); // Clear previous renderList
  46202. var sceneMeshes = this.getScene().meshes;
  46203. for (var index = 0; index < sceneMeshes.length; index++) {
  46204. var mesh = sceneMeshes[index];
  46205. if (this.renderListPredicate(mesh)) {
  46206. this.renderList.push(mesh);
  46207. }
  46208. }
  46209. }
  46210. if (this.renderList && this.renderList.length === 0) {
  46211. return;
  46212. }
  46213. this.onBeforeBindObservable.notifyObservers(this);
  46214. // Set custom projection.
  46215. // Needs to be before binding to prevent changing the aspect ratio.
  46216. var camera;
  46217. if (this.activeCamera) {
  46218. camera = this.activeCamera;
  46219. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  46220. if (this.activeCamera !== scene.activeCamera) {
  46221. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  46222. }
  46223. }
  46224. else {
  46225. camera = scene.activeCamera;
  46226. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  46227. }
  46228. // Prepare renderingManager
  46229. this._renderingManager.reset();
  46230. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  46231. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  46232. var sceneRenderId = scene.getRenderId();
  46233. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  46234. var mesh = currentRenderList[meshIndex];
  46235. if (mesh) {
  46236. if (!mesh.isReady()) {
  46237. // Reset _currentRefreshId
  46238. this.resetRefreshCounter();
  46239. continue;
  46240. }
  46241. mesh._preActivateForIntermediateRendering(sceneRenderId);
  46242. var isMasked = void 0;
  46243. if (!this.renderList) {
  46244. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  46245. }
  46246. else {
  46247. isMasked = false;
  46248. }
  46249. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  46250. mesh._activate(sceneRenderId);
  46251. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  46252. var subMesh = mesh.subMeshes[subIndex];
  46253. scene._activeIndices.addCount(subMesh.indexCount, false);
  46254. this._renderingManager.dispatch(subMesh);
  46255. }
  46256. }
  46257. }
  46258. }
  46259. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  46260. var particleSystem = scene.particleSystems[particleIndex];
  46261. var emitter = particleSystem.emitter;
  46262. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  46263. continue;
  46264. }
  46265. if (currentRenderList.indexOf(emitter) >= 0) {
  46266. this._renderingManager.dispatchParticles(particleSystem);
  46267. }
  46268. }
  46269. if (this.isCube) {
  46270. for (var face = 0; face < 6; face++) {
  46271. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46272. scene.incrementRenderId();
  46273. scene.resetCachedMaterial();
  46274. }
  46275. }
  46276. else {
  46277. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46278. }
  46279. this.onAfterUnbindObservable.notifyObservers(this);
  46280. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  46281. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  46282. }
  46283. engine.setViewport(scene.activeCamera.viewport);
  46284. scene.resetCachedMaterial();
  46285. };
  46286. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  46287. var _this = this;
  46288. var scene = this.getScene();
  46289. var engine = scene.getEngine();
  46290. // Bind
  46291. if (this._postProcessManager) {
  46292. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  46293. }
  46294. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  46295. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  46296. }
  46297. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  46298. // Clear
  46299. if (this.onClearObservable.hasObservers()) {
  46300. this.onClearObservable.notifyObservers(engine);
  46301. }
  46302. else {
  46303. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  46304. }
  46305. if (!this._doNotChangeAspectRatio) {
  46306. scene.updateTransformMatrix(true);
  46307. }
  46308. // Render
  46309. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  46310. if (this._postProcessManager) {
  46311. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  46312. }
  46313. else if (useCameraPostProcess) {
  46314. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  46315. }
  46316. if (!this._doNotChangeAspectRatio) {
  46317. scene.updateTransformMatrix(true);
  46318. }
  46319. // Dump ?
  46320. if (dumpForDebug) {
  46321. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  46322. }
  46323. // Unbind
  46324. if (!this.isCube || faceIndex === 5) {
  46325. if (this.isCube) {
  46326. if (faceIndex === 5) {
  46327. engine.generateMipMapsForCubemap(this._texture);
  46328. }
  46329. }
  46330. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  46331. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  46332. });
  46333. }
  46334. else {
  46335. this.onAfterRenderObservable.notifyObservers(faceIndex);
  46336. }
  46337. };
  46338. /**
  46339. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  46340. * This allowed control for front to back rendering or reversly depending of the special needs.
  46341. *
  46342. * @param renderingGroupId The rendering group id corresponding to its index
  46343. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  46344. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  46345. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  46346. */
  46347. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  46348. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  46349. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  46350. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  46351. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  46352. };
  46353. /**
  46354. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  46355. *
  46356. * @param renderingGroupId The rendering group id corresponding to its index
  46357. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  46358. */
  46359. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  46360. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  46361. };
  46362. RenderTargetTexture.prototype.clone = function () {
  46363. var textureSize = this.getSize();
  46364. 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);
  46365. // Base texture
  46366. newTexture.hasAlpha = this.hasAlpha;
  46367. newTexture.level = this.level;
  46368. // RenderTarget Texture
  46369. newTexture.coordinatesMode = this.coordinatesMode;
  46370. newTexture.renderList = this.renderList.slice(0);
  46371. return newTexture;
  46372. };
  46373. RenderTargetTexture.prototype.serialize = function () {
  46374. if (!this.name) {
  46375. return null;
  46376. }
  46377. var serializationObject = _super.prototype.serialize.call(this);
  46378. serializationObject.renderTargetSize = this.getRenderSize();
  46379. serializationObject.renderList = [];
  46380. for (var index = 0; index < this.renderList.length; index++) {
  46381. serializationObject.renderList.push(this.renderList[index].id);
  46382. }
  46383. return serializationObject;
  46384. };
  46385. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  46386. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  46387. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  46388. };
  46389. RenderTargetTexture.prototype.dispose = function () {
  46390. if (this._postProcessManager) {
  46391. this._postProcessManager.dispose();
  46392. this._postProcessManager = null;
  46393. }
  46394. this.clearPostProcesses(true);
  46395. this.renderList = null;
  46396. // Remove from custom render targets
  46397. var scene = this.getScene();
  46398. var index = scene.customRenderTargets.indexOf(this);
  46399. if (index >= 0) {
  46400. scene.customRenderTargets.splice(index, 1);
  46401. }
  46402. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  46403. var camera = _a[_i];
  46404. index = camera.customRenderTargets.indexOf(this);
  46405. if (index >= 0) {
  46406. camera.customRenderTargets.splice(index, 1);
  46407. }
  46408. }
  46409. _super.prototype.dispose.call(this);
  46410. };
  46411. RenderTargetTexture.prototype._rebuild = function () {
  46412. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  46413. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  46414. }
  46415. if (this._postProcessManager) {
  46416. this._postProcessManager._rebuild();
  46417. }
  46418. };
  46419. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  46420. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  46421. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  46422. return RenderTargetTexture;
  46423. }(BABYLON.Texture));
  46424. BABYLON.RenderTargetTexture = RenderTargetTexture;
  46425. })(BABYLON || (BABYLON = {}));
  46426. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  46427. var BABYLON;
  46428. (function (BABYLON) {
  46429. ;
  46430. var MultiRenderTarget = (function (_super) {
  46431. __extends(MultiRenderTarget, _super);
  46432. function MultiRenderTarget(name, size, count, scene, options) {
  46433. var _this = this;
  46434. options = options || {};
  46435. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  46436. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  46437. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  46438. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  46439. if (!_this.isSupported) {
  46440. _this.dispose();
  46441. return;
  46442. }
  46443. var types = [];
  46444. var samplingModes = [];
  46445. for (var i = 0; i < count; i++) {
  46446. if (options.types && options.types[i]) {
  46447. types.push(options.types[i]);
  46448. }
  46449. else {
  46450. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  46451. }
  46452. if (options.samplingModes && options.samplingModes[i]) {
  46453. samplingModes.push(options.samplingModes[i]);
  46454. }
  46455. else {
  46456. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46457. }
  46458. }
  46459. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  46460. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  46461. _this._count = count;
  46462. _this._size = size;
  46463. _this._multiRenderTargetOptions = {
  46464. samplingModes: samplingModes,
  46465. generateMipMaps: generateMipMaps,
  46466. generateDepthBuffer: generateDepthBuffer,
  46467. generateStencilBuffer: generateStencilBuffer,
  46468. generateDepthTexture: generateDepthTexture,
  46469. types: types,
  46470. textureCount: count
  46471. };
  46472. _this._createInternalTextures();
  46473. _this._createTextures();
  46474. return _this;
  46475. }
  46476. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  46477. get: function () {
  46478. var engine = this.getScene().getEngine();
  46479. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  46480. },
  46481. enumerable: true,
  46482. configurable: true
  46483. });
  46484. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  46485. get: function () {
  46486. return this._textures;
  46487. },
  46488. enumerable: true,
  46489. configurable: true
  46490. });
  46491. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  46492. get: function () {
  46493. return this._textures[this._textures.length - 1];
  46494. },
  46495. enumerable: true,
  46496. configurable: true
  46497. });
  46498. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  46499. set: function (wrap) {
  46500. if (this._textures) {
  46501. for (var i = 0; i < this._textures.length; i++) {
  46502. this._textures[i].wrapU = wrap;
  46503. }
  46504. }
  46505. },
  46506. enumerable: true,
  46507. configurable: true
  46508. });
  46509. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  46510. set: function (wrap) {
  46511. if (this._textures) {
  46512. for (var i = 0; i < this._textures.length; i++) {
  46513. this._textures[i].wrapV = wrap;
  46514. }
  46515. }
  46516. },
  46517. enumerable: true,
  46518. configurable: true
  46519. });
  46520. MultiRenderTarget.prototype._rebuild = function () {
  46521. this.releaseInternalTextures();
  46522. this._createInternalTextures();
  46523. for (var i = 0; i < this._internalTextures.length; i++) {
  46524. var texture = this._textures[i];
  46525. texture._texture = this._internalTextures[i];
  46526. }
  46527. // Keeps references to frame buffer and stencil/depth buffer
  46528. this._texture = this._internalTextures[0];
  46529. };
  46530. MultiRenderTarget.prototype._createInternalTextures = function () {
  46531. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  46532. };
  46533. MultiRenderTarget.prototype._createTextures = function () {
  46534. this._textures = [];
  46535. for (var i = 0; i < this._internalTextures.length; i++) {
  46536. var texture = new BABYLON.Texture(null, this.getScene());
  46537. texture._texture = this._internalTextures[i];
  46538. this._textures.push(texture);
  46539. }
  46540. // Keeps references to frame buffer and stencil/depth buffer
  46541. this._texture = this._internalTextures[0];
  46542. };
  46543. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  46544. get: function () {
  46545. return this._samples;
  46546. },
  46547. set: function (value) {
  46548. if (this._samples === value) {
  46549. return;
  46550. }
  46551. for (var i = 0; i < this._internalTextures.length; i++) {
  46552. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  46553. }
  46554. },
  46555. enumerable: true,
  46556. configurable: true
  46557. });
  46558. MultiRenderTarget.prototype.resize = function (size) {
  46559. this.releaseInternalTextures();
  46560. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  46561. this._createInternalTextures();
  46562. };
  46563. MultiRenderTarget.prototype.dispose = function () {
  46564. this.releaseInternalTextures();
  46565. _super.prototype.dispose.call(this);
  46566. };
  46567. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  46568. if (!this._internalTextures) {
  46569. return;
  46570. }
  46571. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  46572. if (this._internalTextures[i] !== undefined) {
  46573. this._internalTextures[i].dispose();
  46574. this._internalTextures.splice(i, 1);
  46575. }
  46576. }
  46577. };
  46578. return MultiRenderTarget;
  46579. }(BABYLON.RenderTargetTexture));
  46580. BABYLON.MultiRenderTarget = MultiRenderTarget;
  46581. })(BABYLON || (BABYLON = {}));
  46582. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  46583. /// <reference path="babylon.renderTargetTexture.ts" />
  46584. var BABYLON;
  46585. (function (BABYLON) {
  46586. var MirrorTexture = (function (_super) {
  46587. __extends(MirrorTexture, _super);
  46588. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  46589. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46590. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46591. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  46592. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  46593. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  46594. _this._transformMatrix = BABYLON.Matrix.Zero();
  46595. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  46596. _this._blurKernelX = 0;
  46597. _this._blurKernelY = 0;
  46598. _this._blurRatio = 1.0;
  46599. _this.ignoreCameraViewport = true;
  46600. _this.onBeforeRenderObservable.add(function () {
  46601. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  46602. _this._savedViewMatrix = scene.getViewMatrix();
  46603. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  46604. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  46605. scene.clipPlane = _this.mirrorPlane;
  46606. scene.getEngine().cullBackFaces = false;
  46607. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  46608. });
  46609. _this.onAfterRenderObservable.add(function () {
  46610. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  46611. scene.getEngine().cullBackFaces = true;
  46612. scene._mirroredCameraPosition = null;
  46613. delete scene.clipPlane;
  46614. });
  46615. return _this;
  46616. }
  46617. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  46618. get: function () {
  46619. return this._blurRatio;
  46620. },
  46621. set: function (value) {
  46622. if (this._blurRatio === value) {
  46623. return;
  46624. }
  46625. this._blurRatio = value;
  46626. this._preparePostProcesses();
  46627. },
  46628. enumerable: true,
  46629. configurable: true
  46630. });
  46631. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  46632. set: function (value) {
  46633. this.blurKernelX = value;
  46634. this.blurKernelY = value;
  46635. },
  46636. enumerable: true,
  46637. configurable: true
  46638. });
  46639. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  46640. get: function () {
  46641. return this._blurKernelX;
  46642. },
  46643. set: function (value) {
  46644. if (this._blurKernelX === value) {
  46645. return;
  46646. }
  46647. this._blurKernelX = value;
  46648. this._preparePostProcesses();
  46649. },
  46650. enumerable: true,
  46651. configurable: true
  46652. });
  46653. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  46654. get: function () {
  46655. return this._blurKernelY;
  46656. },
  46657. set: function (value) {
  46658. if (this._blurKernelY === value) {
  46659. return;
  46660. }
  46661. this._blurKernelY = value;
  46662. this._preparePostProcesses();
  46663. },
  46664. enumerable: true,
  46665. configurable: true
  46666. });
  46667. MirrorTexture.prototype._preparePostProcesses = function () {
  46668. this.clearPostProcesses(true);
  46669. if (this._blurKernelX && this._blurKernelY) {
  46670. var engine = this.getScene().getEngine();
  46671. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46672. 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);
  46673. this._blurX.autoClear = false;
  46674. if (this._blurRatio === 1 && this.samples < 2) {
  46675. this._blurX.outputTexture = this._texture;
  46676. }
  46677. else {
  46678. this._blurX.alwaysForcePOT = true;
  46679. }
  46680. 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);
  46681. this._blurY.autoClear = false;
  46682. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  46683. this.addPostProcess(this._blurX);
  46684. this.addPostProcess(this._blurY);
  46685. }
  46686. };
  46687. MirrorTexture.prototype.clone = function () {
  46688. var textureSize = this.getSize();
  46689. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  46690. // Base texture
  46691. newTexture.hasAlpha = this.hasAlpha;
  46692. newTexture.level = this.level;
  46693. // Mirror Texture
  46694. newTexture.mirrorPlane = this.mirrorPlane.clone();
  46695. newTexture.renderList = this.renderList.slice(0);
  46696. return newTexture;
  46697. };
  46698. MirrorTexture.prototype.serialize = function () {
  46699. if (!this.name) {
  46700. return null;
  46701. }
  46702. var serializationObject = _super.prototype.serialize.call(this);
  46703. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  46704. return serializationObject;
  46705. };
  46706. return MirrorTexture;
  46707. }(BABYLON.RenderTargetTexture));
  46708. BABYLON.MirrorTexture = MirrorTexture;
  46709. })(BABYLON || (BABYLON = {}));
  46710. //# sourceMappingURL=babylon.mirrorTexture.js.map
  46711. /// <reference path="babylon.renderTargetTexture.ts" />
  46712. var BABYLON;
  46713. (function (BABYLON) {
  46714. /**
  46715. * Creates a refraction texture used by refraction channel of the standard material.
  46716. * @param name the texture name
  46717. * @param size size of the underlying texture
  46718. * @param scene root scene
  46719. */
  46720. var RefractionTexture = (function (_super) {
  46721. __extends(RefractionTexture, _super);
  46722. function RefractionTexture(name, size, scene, generateMipMaps) {
  46723. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  46724. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  46725. _this.depth = 2.0;
  46726. _this.onBeforeRenderObservable.add(function () {
  46727. scene.clipPlane = _this.refractionPlane;
  46728. });
  46729. _this.onAfterRenderObservable.add(function () {
  46730. delete scene.clipPlane;
  46731. });
  46732. return _this;
  46733. }
  46734. RefractionTexture.prototype.clone = function () {
  46735. var textureSize = this.getSize();
  46736. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  46737. // Base texture
  46738. newTexture.hasAlpha = this.hasAlpha;
  46739. newTexture.level = this.level;
  46740. // Refraction Texture
  46741. newTexture.refractionPlane = this.refractionPlane.clone();
  46742. newTexture.renderList = this.renderList.slice(0);
  46743. newTexture.depth = this.depth;
  46744. return newTexture;
  46745. };
  46746. RefractionTexture.prototype.serialize = function () {
  46747. if (!this.name) {
  46748. return null;
  46749. }
  46750. var serializationObject = _super.prototype.serialize.call(this);
  46751. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  46752. serializationObject.depth = this.depth;
  46753. return serializationObject;
  46754. };
  46755. return RefractionTexture;
  46756. }(BABYLON.RenderTargetTexture));
  46757. BABYLON.RefractionTexture = RefractionTexture;
  46758. })(BABYLON || (BABYLON = {}));
  46759. //# sourceMappingURL=babylon.refractionTexture.js.map
  46760. /// <reference path="babylon.texture.ts" />
  46761. var BABYLON;
  46762. (function (BABYLON) {
  46763. var DynamicTexture = (function (_super) {
  46764. __extends(DynamicTexture, _super);
  46765. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  46766. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46767. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  46768. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  46769. _this.name = name;
  46770. var engine = _this.getScene().getEngine();
  46771. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46772. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46773. _this._generateMipMaps = generateMipMaps;
  46774. if (options.getContext) {
  46775. _this._canvas = options;
  46776. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46777. }
  46778. else {
  46779. _this._canvas = document.createElement("canvas");
  46780. if (options.width) {
  46781. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46782. }
  46783. else {
  46784. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  46785. }
  46786. }
  46787. var textureSize = _this.getSize();
  46788. _this._canvas.width = textureSize.width;
  46789. _this._canvas.height = textureSize.height;
  46790. _this._context = _this._canvas.getContext("2d");
  46791. return _this;
  46792. }
  46793. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  46794. get: function () {
  46795. return true;
  46796. },
  46797. enumerable: true,
  46798. configurable: true
  46799. });
  46800. DynamicTexture.prototype._recreate = function (textureSize) {
  46801. this._canvas.width = textureSize.width;
  46802. this._canvas.height = textureSize.height;
  46803. this.releaseInternalTexture();
  46804. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  46805. };
  46806. DynamicTexture.prototype.scale = function (ratio) {
  46807. var textureSize = this.getSize();
  46808. textureSize.width *= ratio;
  46809. textureSize.height *= ratio;
  46810. this._recreate(textureSize);
  46811. };
  46812. DynamicTexture.prototype.scaleTo = function (width, height) {
  46813. var textureSize = this.getSize();
  46814. textureSize.width = width;
  46815. textureSize.height = height;
  46816. this._recreate(textureSize);
  46817. };
  46818. DynamicTexture.prototype.getContext = function () {
  46819. return this._context;
  46820. };
  46821. DynamicTexture.prototype.clear = function () {
  46822. var size = this.getSize();
  46823. this._context.fillRect(0, 0, size.width, size.height);
  46824. };
  46825. DynamicTexture.prototype.update = function (invertY) {
  46826. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  46827. };
  46828. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  46829. if (update === void 0) { update = true; }
  46830. var size = this.getSize();
  46831. if (clearColor) {
  46832. this._context.fillStyle = clearColor;
  46833. this._context.fillRect(0, 0, size.width, size.height);
  46834. }
  46835. this._context.font = font;
  46836. if (x === null || x === undefined) {
  46837. var textSize = this._context.measureText(text);
  46838. x = (size.width - textSize.width) / 2;
  46839. }
  46840. if (y === null || y === undefined) {
  46841. var fontSize = parseInt((font.replace(/\D/g, '')));
  46842. ;
  46843. y = (size.height / 2) + (fontSize / 3.65);
  46844. }
  46845. this._context.fillStyle = color;
  46846. this._context.fillText(text, x, y);
  46847. if (update) {
  46848. this.update(invertY);
  46849. }
  46850. };
  46851. DynamicTexture.prototype.clone = function () {
  46852. var textureSize = this.getSize();
  46853. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  46854. // Base texture
  46855. newTexture.hasAlpha = this.hasAlpha;
  46856. newTexture.level = this.level;
  46857. // Dynamic Texture
  46858. newTexture.wrapU = this.wrapU;
  46859. newTexture.wrapV = this.wrapV;
  46860. return newTexture;
  46861. };
  46862. DynamicTexture.prototype._rebuild = function () {
  46863. this.update();
  46864. };
  46865. return DynamicTexture;
  46866. }(BABYLON.Texture));
  46867. BABYLON.DynamicTexture = DynamicTexture;
  46868. })(BABYLON || (BABYLON = {}));
  46869. //# sourceMappingURL=babylon.dynamicTexture.js.map
  46870. var BABYLON;
  46871. (function (BABYLON) {
  46872. var VideoTexture = (function (_super) {
  46873. __extends(VideoTexture, _super);
  46874. /**
  46875. * Creates a video texture.
  46876. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  46877. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  46878. * @param {BABYLON.Scene} scene is obviously the current scene.
  46879. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  46880. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  46881. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  46882. */
  46883. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  46884. if (generateMipMaps === void 0) { generateMipMaps = false; }
  46885. if (invertY === void 0) { invertY = false; }
  46886. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46887. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46888. _this._autoLaunch = true;
  46889. var urls;
  46890. _this.name = name;
  46891. if (urlsOrVideo instanceof HTMLVideoElement) {
  46892. _this.video = urlsOrVideo;
  46893. }
  46894. else {
  46895. urls = urlsOrVideo;
  46896. _this.video = document.createElement("video");
  46897. _this.video.autoplay = false;
  46898. _this.video.loop = true;
  46899. }
  46900. _this._generateMipMaps = generateMipMaps;
  46901. _this._samplingMode = samplingMode;
  46902. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  46903. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46904. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46905. }
  46906. else {
  46907. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46908. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46909. _this._generateMipMaps = false;
  46910. }
  46911. if (urls) {
  46912. _this.video.addEventListener("canplay", function () {
  46913. _this._createTexture();
  46914. });
  46915. urls.forEach(function (url) {
  46916. var source = document.createElement("source");
  46917. source.src = url;
  46918. _this.video.appendChild(source);
  46919. });
  46920. }
  46921. else {
  46922. _this._createTexture();
  46923. }
  46924. _this._lastUpdate = BABYLON.Tools.Now;
  46925. return _this;
  46926. }
  46927. VideoTexture.prototype.__setTextureReady = function () {
  46928. this._texture.isReady = true;
  46929. };
  46930. VideoTexture.prototype._createTexture = function () {
  46931. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  46932. if (this._autoLaunch) {
  46933. this._autoLaunch = false;
  46934. this.video.play();
  46935. }
  46936. this._setTextureReady = this.__setTextureReady.bind(this);
  46937. this.video.addEventListener("playing", this._setTextureReady);
  46938. };
  46939. VideoTexture.prototype._rebuild = function () {
  46940. this.update();
  46941. };
  46942. VideoTexture.prototype.update = function () {
  46943. var now = BABYLON.Tools.Now;
  46944. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  46945. return false;
  46946. }
  46947. this._lastUpdate = now;
  46948. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  46949. return true;
  46950. };
  46951. VideoTexture.prototype.dispose = function () {
  46952. _super.prototype.dispose.call(this);
  46953. this.video.removeEventListener("playing", this._setTextureReady);
  46954. };
  46955. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  46956. var video = document.createElement("video");
  46957. var constraintsDeviceId;
  46958. if (constraints && constraints.deviceId) {
  46959. constraintsDeviceId = {
  46960. exact: constraints.deviceId
  46961. };
  46962. }
  46963. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  46964. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  46965. if (navigator.getUserMedia) {
  46966. navigator.getUserMedia({
  46967. video: {
  46968. deviceId: constraintsDeviceId,
  46969. width: {
  46970. min: (constraints && constraints.minWidth) || 256,
  46971. max: (constraints && constraints.maxWidth) || 640
  46972. },
  46973. height: {
  46974. min: (constraints && constraints.minHeight) || 256,
  46975. max: (constraints && constraints.maxHeight) || 480
  46976. }
  46977. }
  46978. }, function (stream) {
  46979. if (video.mozSrcObject !== undefined) {
  46980. video.mozSrcObject = stream;
  46981. }
  46982. else {
  46983. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  46984. }
  46985. video.play();
  46986. if (onReady) {
  46987. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  46988. }
  46989. }, function (e) {
  46990. BABYLON.Tools.Error(e.name);
  46991. });
  46992. }
  46993. };
  46994. return VideoTexture;
  46995. }(BABYLON.Texture));
  46996. BABYLON.VideoTexture = VideoTexture;
  46997. })(BABYLON || (BABYLON = {}));
  46998. //# sourceMappingURL=babylon.videoTexture.js.map
  46999. var BABYLON;
  47000. (function (BABYLON) {
  47001. var RawTexture = (function (_super) {
  47002. __extends(RawTexture, _super);
  47003. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  47004. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47005. if (invertY === void 0) { invertY = false; }
  47006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47007. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  47008. _this.format = format;
  47009. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  47010. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47011. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47012. return _this;
  47013. }
  47014. RawTexture.prototype.update = function (data) {
  47015. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  47016. };
  47017. // Statics
  47018. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47019. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47020. if (invertY === void 0) { invertY = false; }
  47021. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47022. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  47023. };
  47024. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47025. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47026. if (invertY === void 0) { invertY = false; }
  47027. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47028. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  47029. };
  47030. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47031. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47032. if (invertY === void 0) { invertY = false; }
  47033. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47034. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  47035. };
  47036. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47037. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47038. if (invertY === void 0) { invertY = false; }
  47039. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47040. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  47041. };
  47042. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47043. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47044. if (invertY === void 0) { invertY = false; }
  47045. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47046. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  47047. };
  47048. return RawTexture;
  47049. }(BABYLON.Texture));
  47050. BABYLON.RawTexture = RawTexture;
  47051. })(BABYLON || (BABYLON = {}));
  47052. //# sourceMappingURL=babylon.rawTexture.js.map
  47053. var BABYLON;
  47054. (function (BABYLON) {
  47055. var PostProcess = (function () {
  47056. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  47057. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  47058. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47059. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  47060. if (blockCompilation === void 0) { blockCompilation = false; }
  47061. this.name = name;
  47062. this.width = -1;
  47063. this.height = -1;
  47064. this.autoClear = true;
  47065. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  47066. /*
  47067. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  47068. Can only be used on a single postprocess or on the last one of a chain.
  47069. */
  47070. this.enablePixelPerfectMode = false;
  47071. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  47072. this.alwaysForcePOT = false;
  47073. this.samples = 1;
  47074. this.adaptScaleToCurrentViewport = false;
  47075. this._reusable = false;
  47076. this._textures = new BABYLON.SmartArray(2);
  47077. this._currentRenderTextureInd = 0;
  47078. this._scaleRatio = new BABYLON.Vector2(1, 1);
  47079. this._texelSize = BABYLON.Vector2.Zero();
  47080. // Events
  47081. /**
  47082. * An event triggered when the postprocess is activated.
  47083. * @type {BABYLON.Observable}
  47084. */
  47085. this.onActivateObservable = new BABYLON.Observable();
  47086. /**
  47087. * An event triggered when the postprocess changes its size.
  47088. * @type {BABYLON.Observable}
  47089. */
  47090. this.onSizeChangedObservable = new BABYLON.Observable();
  47091. /**
  47092. * An event triggered when the postprocess applies its effect.
  47093. * @type {BABYLON.Observable}
  47094. */
  47095. this.onApplyObservable = new BABYLON.Observable();
  47096. /**
  47097. * An event triggered before rendering the postprocess
  47098. * @type {BABYLON.Observable}
  47099. */
  47100. this.onBeforeRenderObservable = new BABYLON.Observable();
  47101. /**
  47102. * An event triggered after rendering the postprocess
  47103. * @type {BABYLON.Observable}
  47104. */
  47105. this.onAfterRenderObservable = new BABYLON.Observable();
  47106. if (camera != null) {
  47107. this._camera = camera;
  47108. this._scene = camera.getScene();
  47109. camera.attachPostProcess(this);
  47110. this._engine = this._scene.getEngine();
  47111. this._scene.postProcesses.push(this);
  47112. }
  47113. else {
  47114. this._engine = engine;
  47115. this._engine.postProcesses.push(this);
  47116. }
  47117. this._options = options;
  47118. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  47119. this._reusable = reusable || false;
  47120. this._textureType = textureType;
  47121. this._samplers = samplers || [];
  47122. this._samplers.push("textureSampler");
  47123. this._fragmentUrl = fragmentUrl;
  47124. this._vertexUrl = vertexUrl;
  47125. this._parameters = parameters || [];
  47126. this._parameters.push("scale");
  47127. this._indexParameters = indexParameters;
  47128. if (!blockCompilation) {
  47129. this.updateEffect(defines);
  47130. }
  47131. }
  47132. Object.defineProperty(PostProcess.prototype, "onActivate", {
  47133. set: function (callback) {
  47134. if (this._onActivateObserver) {
  47135. this.onActivateObservable.remove(this._onActivateObserver);
  47136. }
  47137. this._onActivateObserver = this.onActivateObservable.add(callback);
  47138. },
  47139. enumerable: true,
  47140. configurable: true
  47141. });
  47142. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  47143. set: function (callback) {
  47144. if (this._onSizeChangedObserver) {
  47145. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  47146. }
  47147. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  47148. },
  47149. enumerable: true,
  47150. configurable: true
  47151. });
  47152. Object.defineProperty(PostProcess.prototype, "onApply", {
  47153. set: function (callback) {
  47154. if (this._onApplyObserver) {
  47155. this.onApplyObservable.remove(this._onApplyObserver);
  47156. }
  47157. this._onApplyObserver = this.onApplyObservable.add(callback);
  47158. },
  47159. enumerable: true,
  47160. configurable: true
  47161. });
  47162. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  47163. set: function (callback) {
  47164. if (this._onBeforeRenderObserver) {
  47165. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  47166. }
  47167. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  47168. },
  47169. enumerable: true,
  47170. configurable: true
  47171. });
  47172. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  47173. set: function (callback) {
  47174. if (this._onAfterRenderObserver) {
  47175. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  47176. }
  47177. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  47178. },
  47179. enumerable: true,
  47180. configurable: true
  47181. });
  47182. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  47183. get: function () {
  47184. return this._textures.data[this._currentRenderTextureInd];
  47185. },
  47186. set: function (value) {
  47187. this._forcedOutputTexture = value;
  47188. },
  47189. enumerable: true,
  47190. configurable: true
  47191. });
  47192. PostProcess.prototype.getCamera = function () {
  47193. return this._camera;
  47194. };
  47195. Object.defineProperty(PostProcess.prototype, "texelSize", {
  47196. get: function () {
  47197. if (this._shareOutputWithPostProcess) {
  47198. return this._shareOutputWithPostProcess.texelSize;
  47199. }
  47200. if (this._forcedOutputTexture) {
  47201. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  47202. }
  47203. return this._texelSize;
  47204. },
  47205. enumerable: true,
  47206. configurable: true
  47207. });
  47208. PostProcess.prototype.getEngine = function () {
  47209. return this._engine;
  47210. };
  47211. PostProcess.prototype.getEffect = function () {
  47212. return this._effect;
  47213. };
  47214. PostProcess.prototype.shareOutputWith = function (postProcess) {
  47215. this._disposeTextures();
  47216. this._shareOutputWithPostProcess = postProcess;
  47217. return this;
  47218. };
  47219. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  47220. 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);
  47221. };
  47222. PostProcess.prototype.isReusable = function () {
  47223. return this._reusable;
  47224. };
  47225. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  47226. PostProcess.prototype.markTextureDirty = function () {
  47227. this.width = -1;
  47228. };
  47229. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  47230. var _this = this;
  47231. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  47232. camera = camera || this._camera;
  47233. var scene = camera.getScene();
  47234. var engine = scene.getEngine();
  47235. var maxSize = engine.getCaps().maxTextureSize;
  47236. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  47237. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  47238. var desiredWidth = (this._options.width || requiredWidth);
  47239. var desiredHeight = this._options.height || requiredHeight;
  47240. if (this.adaptScaleToCurrentViewport) {
  47241. var currentViewport = engine.currentViewport;
  47242. if (currentViewport) {
  47243. desiredWidth *= currentViewport.width;
  47244. desiredHeight *= currentViewport.height;
  47245. }
  47246. }
  47247. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  47248. if (!this._options.width) {
  47249. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  47250. }
  47251. if (!this._options.height) {
  47252. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  47253. }
  47254. }
  47255. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  47256. if (this._textures.length > 0) {
  47257. for (var i = 0; i < this._textures.length; i++) {
  47258. this._engine._releaseTexture(this._textures.data[i]);
  47259. }
  47260. this._textures.reset();
  47261. }
  47262. this.width = desiredWidth;
  47263. this.height = desiredHeight;
  47264. var textureSize = { width: this.width, height: this.height };
  47265. var textureOptions = {
  47266. generateMipMaps: false,
  47267. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  47268. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  47269. samplingMode: this.renderTargetSamplingMode,
  47270. type: this._textureType
  47271. };
  47272. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47273. if (this._reusable) {
  47274. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47275. }
  47276. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  47277. this.onSizeChangedObservable.notifyObservers(this);
  47278. }
  47279. this._textures.forEach(function (texture) {
  47280. if (texture.samples !== _this.samples) {
  47281. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  47282. }
  47283. });
  47284. }
  47285. var target;
  47286. if (this._shareOutputWithPostProcess) {
  47287. target = this._shareOutputWithPostProcess.outputTexture;
  47288. }
  47289. else if (this._forcedOutputTexture) {
  47290. target = this._forcedOutputTexture;
  47291. this.width = this._forcedOutputTexture.width;
  47292. this.height = this._forcedOutputTexture.height;
  47293. }
  47294. else {
  47295. target = this.outputTexture;
  47296. }
  47297. if (this.enablePixelPerfectMode) {
  47298. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  47299. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  47300. }
  47301. else {
  47302. this._scaleRatio.copyFromFloats(1, 1);
  47303. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  47304. }
  47305. this.onActivateObservable.notifyObservers(camera);
  47306. // Clear
  47307. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  47308. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  47309. }
  47310. if (this._reusable) {
  47311. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  47312. }
  47313. };
  47314. Object.defineProperty(PostProcess.prototype, "isSupported", {
  47315. get: function () {
  47316. return this._effect.isSupported;
  47317. },
  47318. enumerable: true,
  47319. configurable: true
  47320. });
  47321. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  47322. get: function () {
  47323. if (this._shareOutputWithPostProcess) {
  47324. return this._shareOutputWithPostProcess.aspectRatio;
  47325. }
  47326. if (this._forcedOutputTexture) {
  47327. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  47328. }
  47329. return this.width / this.height;
  47330. },
  47331. enumerable: true,
  47332. configurable: true
  47333. });
  47334. PostProcess.prototype.apply = function () {
  47335. // Check
  47336. if (!this._effect || !this._effect.isReady())
  47337. return null;
  47338. // States
  47339. this._engine.enableEffect(this._effect);
  47340. this._engine.setState(false);
  47341. this._engine.setDepthBuffer(false);
  47342. this._engine.setDepthWrite(false);
  47343. // Alpha
  47344. this._engine.setAlphaMode(this.alphaMode);
  47345. if (this.alphaConstants) {
  47346. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  47347. }
  47348. // Texture
  47349. var source;
  47350. if (this._shareOutputWithPostProcess) {
  47351. source = this._shareOutputWithPostProcess.outputTexture;
  47352. }
  47353. else if (this._forcedOutputTexture) {
  47354. source = this._forcedOutputTexture;
  47355. }
  47356. else {
  47357. source = this.outputTexture;
  47358. }
  47359. this._effect._bindTexture("textureSampler", source);
  47360. // Parameters
  47361. this._effect.setVector2("scale", this._scaleRatio);
  47362. this.onApplyObservable.notifyObservers(this._effect);
  47363. return this._effect;
  47364. };
  47365. PostProcess.prototype._disposeTextures = function () {
  47366. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  47367. return;
  47368. }
  47369. if (this._textures.length > 0) {
  47370. for (var i = 0; i < this._textures.length; i++) {
  47371. this._engine._releaseTexture(this._textures.data[i]);
  47372. }
  47373. }
  47374. this._textures.dispose();
  47375. };
  47376. PostProcess.prototype.dispose = function (camera) {
  47377. camera = camera || this._camera;
  47378. this._disposeTextures();
  47379. if (this._scene) {
  47380. var index_1 = this._scene.postProcesses.indexOf(this);
  47381. if (index_1 !== -1) {
  47382. this._scene.postProcesses.splice(index_1, 1);
  47383. }
  47384. }
  47385. else {
  47386. var index_2 = this._engine.postProcesses.indexOf(this);
  47387. if (index_2 !== -1) {
  47388. this._engine.postProcesses.splice(index_2, 1);
  47389. }
  47390. }
  47391. if (!camera) {
  47392. return;
  47393. }
  47394. camera.detachPostProcess(this);
  47395. var index = camera._postProcesses.indexOf(this);
  47396. if (index === 0 && camera._postProcesses.length > 0) {
  47397. this._camera._postProcesses[0].markTextureDirty();
  47398. }
  47399. this.onActivateObservable.clear();
  47400. this.onAfterRenderObservable.clear();
  47401. this.onApplyObservable.clear();
  47402. this.onBeforeRenderObservable.clear();
  47403. this.onSizeChangedObservable.clear();
  47404. };
  47405. return PostProcess;
  47406. }());
  47407. BABYLON.PostProcess = PostProcess;
  47408. })(BABYLON || (BABYLON = {}));
  47409. //# sourceMappingURL=babylon.postProcess.js.map
  47410. var BABYLON;
  47411. (function (BABYLON) {
  47412. var PassPostProcess = (function (_super) {
  47413. __extends(PassPostProcess, _super);
  47414. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  47415. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47416. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  47417. }
  47418. return PassPostProcess;
  47419. }(BABYLON.PostProcess));
  47420. BABYLON.PassPostProcess = PassPostProcess;
  47421. })(BABYLON || (BABYLON = {}));
  47422. //# sourceMappingURL=babylon.passPostProcess.js.map
  47423. var BABYLON;
  47424. (function (BABYLON) {
  47425. var ShadowGenerator = (function () {
  47426. /**
  47427. * Creates a ShadowGenerator object.
  47428. * A ShadowGenerator is the required tool to use the shadows.
  47429. * Each light casting shadows needs to use its own ShadowGenerator.
  47430. * Required parameters :
  47431. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  47432. * - `light`: the light object generating the shadows.
  47433. * - `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.
  47434. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  47435. */
  47436. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  47437. // Members
  47438. this._bias = 0.00005;
  47439. this._blurBoxOffset = 1;
  47440. this._blurScale = 2;
  47441. this._blurKernel = 1;
  47442. this._useKernelBlur = false;
  47443. this._filter = ShadowGenerator.FILTER_NONE;
  47444. this._darkness = 0;
  47445. this._transparencyShadow = false;
  47446. /**
  47447. * Controls the extent to which the shadows fade out at the edge of the frustum
  47448. * Used only by directionals and spots
  47449. */
  47450. this.frustumEdgeFalloff = 0;
  47451. this.forceBackFacesOnly = false;
  47452. this._lightDirection = BABYLON.Vector3.Zero();
  47453. this._viewMatrix = BABYLON.Matrix.Zero();
  47454. this._projectionMatrix = BABYLON.Matrix.Zero();
  47455. this._transformMatrix = BABYLON.Matrix.Zero();
  47456. this._worldViewProjection = BABYLON.Matrix.Zero();
  47457. this._currentFaceIndex = 0;
  47458. this._currentFaceIndexCache = 0;
  47459. this._isCube = false;
  47460. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  47461. this._mapSize = mapSize;
  47462. this._light = light;
  47463. this._scene = light.getScene();
  47464. light._shadowGenerator = this;
  47465. // Texture type fallback from float to int if not supported.
  47466. var caps = this._scene.getEngine().getCaps();
  47467. if (!useFullFloatFirst) {
  47468. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47469. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47470. }
  47471. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47472. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47473. }
  47474. else {
  47475. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47476. }
  47477. }
  47478. else {
  47479. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47480. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47481. }
  47482. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47483. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47484. }
  47485. else {
  47486. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47487. }
  47488. }
  47489. this._initializeGenerator();
  47490. }
  47491. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  47492. // Static
  47493. get: function () {
  47494. return ShadowGenerator._FILTER_NONE;
  47495. },
  47496. enumerable: true,
  47497. configurable: true
  47498. });
  47499. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  47500. get: function () {
  47501. return ShadowGenerator._FILTER_POISSONSAMPLING;
  47502. },
  47503. enumerable: true,
  47504. configurable: true
  47505. });
  47506. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  47507. get: function () {
  47508. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  47509. },
  47510. enumerable: true,
  47511. configurable: true
  47512. });
  47513. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  47514. get: function () {
  47515. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  47516. },
  47517. enumerable: true,
  47518. configurable: true
  47519. });
  47520. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  47521. get: function () {
  47522. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47523. },
  47524. enumerable: true,
  47525. configurable: true
  47526. });
  47527. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  47528. get: function () {
  47529. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47530. },
  47531. enumerable: true,
  47532. configurable: true
  47533. });
  47534. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  47535. get: function () {
  47536. return this._bias;
  47537. },
  47538. set: function (bias) {
  47539. this._bias = bias;
  47540. },
  47541. enumerable: true,
  47542. configurable: true
  47543. });
  47544. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  47545. get: function () {
  47546. return this._blurBoxOffset;
  47547. },
  47548. set: function (value) {
  47549. if (this._blurBoxOffset === value) {
  47550. return;
  47551. }
  47552. this._blurBoxOffset = value;
  47553. this._disposeBlurPostProcesses();
  47554. },
  47555. enumerable: true,
  47556. configurable: true
  47557. });
  47558. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  47559. get: function () {
  47560. return this._blurScale;
  47561. },
  47562. set: function (value) {
  47563. if (this._blurScale === value) {
  47564. return;
  47565. }
  47566. this._blurScale = value;
  47567. this._disposeBlurPostProcesses();
  47568. },
  47569. enumerable: true,
  47570. configurable: true
  47571. });
  47572. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  47573. get: function () {
  47574. return this._blurKernel;
  47575. },
  47576. set: function (value) {
  47577. if (this._blurKernel === value) {
  47578. return;
  47579. }
  47580. this._blurKernel = value;
  47581. this._disposeBlurPostProcesses();
  47582. },
  47583. enumerable: true,
  47584. configurable: true
  47585. });
  47586. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  47587. get: function () {
  47588. return this._useKernelBlur;
  47589. },
  47590. set: function (value) {
  47591. if (this._useKernelBlur === value) {
  47592. return;
  47593. }
  47594. this._useKernelBlur = value;
  47595. this._disposeBlurPostProcesses();
  47596. },
  47597. enumerable: true,
  47598. configurable: true
  47599. });
  47600. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  47601. get: function () {
  47602. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  47603. },
  47604. set: function (value) {
  47605. this._depthScale = value;
  47606. },
  47607. enumerable: true,
  47608. configurable: true
  47609. });
  47610. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  47611. get: function () {
  47612. return this._filter;
  47613. },
  47614. set: function (value) {
  47615. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  47616. if (this._light.needCube()) {
  47617. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47618. this.useExponentialShadowMap = true;
  47619. return;
  47620. }
  47621. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47622. this.useCloseExponentialShadowMap = true;
  47623. return;
  47624. }
  47625. }
  47626. if (this._filter === value) {
  47627. return;
  47628. }
  47629. this._filter = value;
  47630. this._disposeBlurPostProcesses();
  47631. this._applyFilterValues();
  47632. this._light._markMeshesAsLightDirty();
  47633. },
  47634. enumerable: true,
  47635. configurable: true
  47636. });
  47637. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  47638. get: function () {
  47639. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  47640. },
  47641. set: function (value) {
  47642. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  47643. return;
  47644. }
  47645. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  47646. },
  47647. enumerable: true,
  47648. configurable: true
  47649. });
  47650. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  47651. get: function () {
  47652. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47653. return this.useExponentialShadowMap;
  47654. },
  47655. set: function (value) {
  47656. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47657. this.useExponentialShadowMap = value;
  47658. },
  47659. enumerable: true,
  47660. configurable: true
  47661. });
  47662. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  47663. get: function () {
  47664. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47665. return this.useBlurExponentialShadowMap;
  47666. },
  47667. set: function (value) {
  47668. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47669. this.useBlurExponentialShadowMap = value;
  47670. },
  47671. enumerable: true,
  47672. configurable: true
  47673. });
  47674. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  47675. get: function () {
  47676. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  47677. },
  47678. set: function (value) {
  47679. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  47680. return;
  47681. }
  47682. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47683. },
  47684. enumerable: true,
  47685. configurable: true
  47686. });
  47687. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  47688. get: function () {
  47689. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  47690. },
  47691. set: function (value) {
  47692. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47693. return;
  47694. }
  47695. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47696. },
  47697. enumerable: true,
  47698. configurable: true
  47699. });
  47700. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  47701. get: function () {
  47702. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47703. },
  47704. set: function (value) {
  47705. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  47706. return;
  47707. }
  47708. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47709. },
  47710. enumerable: true,
  47711. configurable: true
  47712. });
  47713. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  47714. get: function () {
  47715. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47716. },
  47717. set: function (value) {
  47718. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47719. return;
  47720. }
  47721. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47722. },
  47723. enumerable: true,
  47724. configurable: true
  47725. });
  47726. /**
  47727. * Returns the darkness value (float).
  47728. */
  47729. ShadowGenerator.prototype.getDarkness = function () {
  47730. return this._darkness;
  47731. };
  47732. /**
  47733. * Sets the ShadowGenerator darkness value (float <= 1.0).
  47734. * Returns the ShadowGenerator.
  47735. */
  47736. ShadowGenerator.prototype.setDarkness = function (darkness) {
  47737. if (darkness >= 1.0)
  47738. this._darkness = 1.0;
  47739. else if (darkness <= 0.0)
  47740. this._darkness = 0.0;
  47741. else
  47742. this._darkness = darkness;
  47743. return this;
  47744. };
  47745. /**
  47746. * Sets the ability to have transparent shadow (boolean).
  47747. * Returns the ShadowGenerator.
  47748. */
  47749. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  47750. this._transparencyShadow = hasShadow;
  47751. return this;
  47752. };
  47753. /**
  47754. * Returns a RenderTargetTexture object : the shadow map texture.
  47755. */
  47756. ShadowGenerator.prototype.getShadowMap = function () {
  47757. return this._shadowMap;
  47758. };
  47759. /**
  47760. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  47761. */
  47762. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  47763. if (this._shadowMap2) {
  47764. return this._shadowMap2;
  47765. }
  47766. return this._shadowMap;
  47767. };
  47768. /**
  47769. * Returns the associated light object.
  47770. */
  47771. ShadowGenerator.prototype.getLight = function () {
  47772. return this._light;
  47773. };
  47774. ShadowGenerator.prototype._initializeGenerator = function () {
  47775. this._light._markMeshesAsLightDirty();
  47776. this._initializeShadowMap();
  47777. };
  47778. ShadowGenerator.prototype._initializeShadowMap = function () {
  47779. var _this = this;
  47780. // Render target
  47781. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  47782. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47783. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47784. this._shadowMap.anisotropicFilteringLevel = 1;
  47785. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47786. this._shadowMap.renderParticles = false;
  47787. this._shadowMap.ignoreCameraViewport = true;
  47788. // Record Face Index before render.
  47789. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  47790. _this._currentFaceIndex = faceIndex;
  47791. });
  47792. // Custom render function.
  47793. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  47794. // Blur if required afer render.
  47795. this._shadowMap.onAfterUnbindObservable.add(function () {
  47796. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  47797. return;
  47798. }
  47799. if (!_this._blurPostProcesses) {
  47800. _this._initializeBlurRTTAndPostProcesses();
  47801. }
  47802. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture(), true);
  47803. });
  47804. // Clear according to the chosen filter.
  47805. this._shadowMap.onClearObservable.add(function (engine) {
  47806. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  47807. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  47808. }
  47809. else {
  47810. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47811. }
  47812. });
  47813. };
  47814. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  47815. var _this = this;
  47816. var engine = this._scene.getEngine();
  47817. var targetSize = this._mapSize / this.blurScale;
  47818. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  47819. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  47820. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47821. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47822. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47823. }
  47824. if (this.useKernelBlur) {
  47825. 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);
  47826. this._kernelBlurXPostprocess.width = targetSize;
  47827. this._kernelBlurXPostprocess.height = targetSize;
  47828. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  47829. effect.setTexture("textureSampler", _this._shadowMap);
  47830. });
  47831. 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);
  47832. this._kernelBlurXPostprocess.autoClear = false;
  47833. this._kernelBlurYPostprocess.autoClear = false;
  47834. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47835. this._kernelBlurXPostprocess.packedFloat = true;
  47836. this._kernelBlurYPostprocess.packedFloat = true;
  47837. }
  47838. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  47839. }
  47840. else {
  47841. 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);
  47842. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  47843. effect.setFloat2("screenSize", targetSize, targetSize);
  47844. effect.setTexture("textureSampler", _this._shadowMap);
  47845. });
  47846. this._boxBlurPostprocess.autoClear = false;
  47847. this._blurPostProcesses = [this._boxBlurPostprocess];
  47848. }
  47849. };
  47850. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  47851. var index;
  47852. var engine = this._scene.getEngine();
  47853. if (depthOnlySubMeshes.length) {
  47854. engine.setColorWrite(false);
  47855. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  47856. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  47857. }
  47858. engine.setColorWrite(true);
  47859. }
  47860. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47861. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  47862. }
  47863. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47864. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  47865. }
  47866. if (this._transparencyShadow) {
  47867. for (index = 0; index < transparentSubMeshes.length; index++) {
  47868. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  47869. }
  47870. }
  47871. };
  47872. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  47873. var _this = this;
  47874. var mesh = subMesh.getRenderingMesh();
  47875. var scene = this._scene;
  47876. var engine = scene.getEngine();
  47877. // Culling
  47878. engine.setState(subMesh.getMaterial().backFaceCulling);
  47879. // Managing instances
  47880. var batch = mesh._getInstancesRenderList(subMesh._id);
  47881. if (batch.mustReturn) {
  47882. return;
  47883. }
  47884. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47885. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  47886. engine.enableEffect(this._effect);
  47887. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47888. var material = subMesh.getMaterial();
  47889. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  47890. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  47891. this._effect.setVector3("lightPosition", this.getLight().position);
  47892. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  47893. // Alpha test
  47894. if (material && material.needAlphaTesting()) {
  47895. var alphaTexture = material.getAlphaTestTexture();
  47896. if (alphaTexture) {
  47897. this._effect.setTexture("diffuseSampler", alphaTexture);
  47898. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  47899. }
  47900. }
  47901. // Bones
  47902. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47903. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47904. }
  47905. if (this.forceBackFacesOnly) {
  47906. engine.setState(true, 0, false, true);
  47907. }
  47908. // Draw
  47909. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47910. if (this.forceBackFacesOnly) {
  47911. engine.setState(true, 0, false, false);
  47912. }
  47913. }
  47914. else {
  47915. // Need to reset refresh rate of the shadowMap
  47916. this._shadowMap.resetRefreshCounter();
  47917. }
  47918. };
  47919. ShadowGenerator.prototype._applyFilterValues = function () {
  47920. if (this.filter === ShadowGenerator.FILTER_NONE) {
  47921. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  47922. }
  47923. else {
  47924. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47925. }
  47926. };
  47927. /**
  47928. * Force shader compilation including textures ready check
  47929. */
  47930. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  47931. var _this = this;
  47932. var scene = this._scene;
  47933. var engine = scene.getEngine();
  47934. var subMeshes = new Array();
  47935. var currentIndex = 0;
  47936. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  47937. var mesh = _a[_i];
  47938. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  47939. }
  47940. var checkReady = function () {
  47941. if (!_this._scene || !_this._scene.getEngine()) {
  47942. return;
  47943. }
  47944. var subMesh = subMeshes[currentIndex];
  47945. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  47946. currentIndex++;
  47947. if (currentIndex >= subMeshes.length) {
  47948. if (onCompiled) {
  47949. onCompiled(_this);
  47950. }
  47951. return;
  47952. }
  47953. }
  47954. setTimeout(checkReady, 16);
  47955. };
  47956. if (subMeshes.length > 0) {
  47957. checkReady();
  47958. }
  47959. };
  47960. /**
  47961. * Boolean : true when the ShadowGenerator is finally computed.
  47962. */
  47963. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  47964. var defines = [];
  47965. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47966. defines.push("#define FLOAT");
  47967. }
  47968. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47969. defines.push("#define ESM");
  47970. }
  47971. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47972. var mesh = subMesh.getMesh();
  47973. var material = subMesh.getMaterial();
  47974. // Alpha test
  47975. if (material && material.needAlphaTesting()) {
  47976. var alphaTexture = material.getAlphaTestTexture();
  47977. if (alphaTexture) {
  47978. defines.push("#define ALPHATEST");
  47979. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47980. attribs.push(BABYLON.VertexBuffer.UVKind);
  47981. defines.push("#define UV1");
  47982. }
  47983. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47984. if (alphaTexture.coordinatesIndex === 1) {
  47985. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47986. defines.push("#define UV2");
  47987. }
  47988. }
  47989. }
  47990. }
  47991. // Bones
  47992. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47993. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47994. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47995. if (mesh.numBoneInfluencers > 4) {
  47996. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47997. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47998. }
  47999. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48000. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48001. }
  48002. else {
  48003. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48004. }
  48005. // Instances
  48006. if (useInstances) {
  48007. defines.push("#define INSTANCES");
  48008. attribs.push("world0");
  48009. attribs.push("world1");
  48010. attribs.push("world2");
  48011. attribs.push("world3");
  48012. }
  48013. // Get correct effect
  48014. var join = defines.join("\n");
  48015. if (this._cachedDefines !== join) {
  48016. this._cachedDefines = join;
  48017. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  48018. }
  48019. return this._effect.isReady();
  48020. };
  48021. /**
  48022. * This creates the defines related to the standard BJS materials.
  48023. */
  48024. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  48025. var scene = this._scene;
  48026. var light = this._light;
  48027. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  48028. return;
  48029. }
  48030. defines["SHADOW" + lightIndex] = true;
  48031. if (this.usePoissonSampling) {
  48032. defines["SHADOWPCF" + lightIndex] = true;
  48033. }
  48034. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  48035. defines["SHADOWESM" + lightIndex] = true;
  48036. }
  48037. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  48038. defines["SHADOWCLOSEESM" + lightIndex] = true;
  48039. }
  48040. if (light.needCube()) {
  48041. defines["SHADOWCUBE" + lightIndex] = true;
  48042. }
  48043. };
  48044. /**
  48045. * This binds shadow lights related to the standard BJS materials.
  48046. * It implies the unifroms available on the materials are the standard BJS ones.
  48047. */
  48048. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  48049. var light = this._light;
  48050. var scene = this._scene;
  48051. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  48052. return;
  48053. }
  48054. if (!light.needCube()) {
  48055. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  48056. }
  48057. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  48058. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  48059. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  48060. };
  48061. // Methods
  48062. /**
  48063. * Returns a Matrix object : the updated transformation matrix.
  48064. */
  48065. ShadowGenerator.prototype.getTransformMatrix = function () {
  48066. var scene = this._scene;
  48067. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  48068. return this._transformMatrix;
  48069. }
  48070. this._currentRenderID = scene.getRenderId();
  48071. this._currentFaceIndexCache = this._currentFaceIndex;
  48072. var lightPosition = this._light.position;
  48073. if (this._light.computeTransformedInformation()) {
  48074. lightPosition = this._light.transformedPosition;
  48075. }
  48076. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  48077. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  48078. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  48079. }
  48080. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  48081. this._cachedPosition = lightPosition.clone();
  48082. this._cachedDirection = this._lightDirection.clone();
  48083. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  48084. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  48085. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  48086. }
  48087. return this._transformMatrix;
  48088. };
  48089. ShadowGenerator.prototype.recreateShadowMap = function () {
  48090. // Track render list.
  48091. var renderList = this._shadowMap.renderList;
  48092. // Clean up existing data.
  48093. this._disposeRTTandPostProcesses();
  48094. // Reinitializes.
  48095. this._initializeGenerator();
  48096. // Reaffect the filter to ensure a correct fallback if necessary.
  48097. this.filter = this.filter;
  48098. // Reaffect the filter.
  48099. this._applyFilterValues();
  48100. // Reaffect Render List.
  48101. this._shadowMap.renderList = renderList;
  48102. };
  48103. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  48104. if (this._shadowMap2) {
  48105. this._shadowMap2.dispose();
  48106. this._shadowMap2 = null;
  48107. }
  48108. if (this._downSamplePostprocess) {
  48109. this._downSamplePostprocess.dispose();
  48110. this._downSamplePostprocess = null;
  48111. }
  48112. if (this._boxBlurPostprocess) {
  48113. this._boxBlurPostprocess.dispose();
  48114. this._boxBlurPostprocess = null;
  48115. }
  48116. if (this._kernelBlurXPostprocess) {
  48117. this._kernelBlurXPostprocess.dispose();
  48118. this._kernelBlurXPostprocess = null;
  48119. }
  48120. if (this._kernelBlurYPostprocess) {
  48121. this._kernelBlurYPostprocess.dispose();
  48122. this._kernelBlurYPostprocess = null;
  48123. }
  48124. this._blurPostProcesses = null;
  48125. };
  48126. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  48127. if (this._shadowMap) {
  48128. this._shadowMap.dispose();
  48129. this._shadowMap = null;
  48130. }
  48131. this._disposeBlurPostProcesses();
  48132. };
  48133. /**
  48134. * Disposes the ShadowGenerator.
  48135. * Returns nothing.
  48136. */
  48137. ShadowGenerator.prototype.dispose = function () {
  48138. this._disposeRTTandPostProcesses();
  48139. this._light._shadowGenerator = null;
  48140. this._light._markMeshesAsLightDirty();
  48141. };
  48142. /**
  48143. * Serializes the ShadowGenerator and returns a serializationObject.
  48144. */
  48145. ShadowGenerator.prototype.serialize = function () {
  48146. var serializationObject = {};
  48147. var shadowMap = this.getShadowMap();
  48148. serializationObject.lightId = this._light.id;
  48149. serializationObject.mapSize = shadowMap.getRenderSize();
  48150. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  48151. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  48152. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  48153. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  48154. serializationObject.usePoissonSampling = this.usePoissonSampling;
  48155. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  48156. serializationObject.depthScale = this.depthScale;
  48157. serializationObject.darkness = this.getDarkness();
  48158. serializationObject.blurBoxOffset = this.blurBoxOffset;
  48159. serializationObject.blurKernel = this.blurKernel;
  48160. serializationObject.blurScale = this.blurScale;
  48161. serializationObject.useKernelBlur = this.useKernelBlur;
  48162. serializationObject.transparencyShadow = this._transparencyShadow;
  48163. serializationObject.renderList = [];
  48164. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  48165. var mesh = shadowMap.renderList[meshIndex];
  48166. serializationObject.renderList.push(mesh.id);
  48167. }
  48168. return serializationObject;
  48169. };
  48170. /**
  48171. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  48172. */
  48173. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  48174. //casting to point light, as light is missing the position attr and typescript complains.
  48175. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  48176. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  48177. var shadowMap = shadowGenerator.getShadowMap();
  48178. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  48179. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  48180. meshes.forEach(function (mesh) {
  48181. shadowMap.renderList.push(mesh);
  48182. });
  48183. }
  48184. if (parsedShadowGenerator.usePoissonSampling) {
  48185. shadowGenerator.usePoissonSampling = true;
  48186. }
  48187. else if (parsedShadowGenerator.useExponentialShadowMap) {
  48188. shadowGenerator.useExponentialShadowMap = true;
  48189. }
  48190. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  48191. shadowGenerator.useBlurExponentialShadowMap = true;
  48192. }
  48193. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  48194. shadowGenerator.useCloseExponentialShadowMap = true;
  48195. }
  48196. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  48197. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  48198. }
  48199. else if (parsedShadowGenerator.useVarianceShadowMap) {
  48200. shadowGenerator.useExponentialShadowMap = true;
  48201. }
  48202. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  48203. shadowGenerator.useBlurExponentialShadowMap = true;
  48204. }
  48205. if (parsedShadowGenerator.depthScale) {
  48206. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  48207. }
  48208. if (parsedShadowGenerator.blurScale) {
  48209. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  48210. }
  48211. if (parsedShadowGenerator.blurBoxOffset) {
  48212. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  48213. }
  48214. if (parsedShadowGenerator.useKernelBlur) {
  48215. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  48216. }
  48217. if (parsedShadowGenerator.blurKernel) {
  48218. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  48219. }
  48220. if (parsedShadowGenerator.bias !== undefined) {
  48221. shadowGenerator.bias = parsedShadowGenerator.bias;
  48222. }
  48223. if (parsedShadowGenerator.darkness) {
  48224. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  48225. }
  48226. if (parsedShadowGenerator.transparencyShadow) {
  48227. shadowGenerator.setTransparencyShadow(true);
  48228. }
  48229. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  48230. return shadowGenerator;
  48231. };
  48232. ShadowGenerator._FILTER_NONE = 0;
  48233. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  48234. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  48235. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  48236. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  48237. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  48238. return ShadowGenerator;
  48239. }());
  48240. BABYLON.ShadowGenerator = ShadowGenerator;
  48241. })(BABYLON || (BABYLON = {}));
  48242. //# sourceMappingURL=babylon.shadowGenerator.js.map
  48243. var BABYLON;
  48244. (function (BABYLON) {
  48245. var DefaultLoadingScreen = (function () {
  48246. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48247. if (_loadingText === void 0) { _loadingText = ""; }
  48248. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  48249. var _this = this;
  48250. this._renderingCanvas = _renderingCanvas;
  48251. this._loadingText = _loadingText;
  48252. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  48253. // Resize
  48254. this._resizeLoadingUI = function () {
  48255. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  48256. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  48257. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  48258. _this._loadingDiv.style.left = canvasRect.left + "px";
  48259. _this._loadingDiv.style.top = canvasRect.top + "px";
  48260. _this._loadingDiv.style.width = canvasRect.width + "px";
  48261. _this._loadingDiv.style.height = canvasRect.height + "px";
  48262. };
  48263. }
  48264. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  48265. if (this._loadingDiv) {
  48266. // Do not add a loading screen if there is already one
  48267. return;
  48268. }
  48269. this._loadingDiv = document.createElement("div");
  48270. this._loadingDiv.id = "babylonjsLoadingDiv";
  48271. this._loadingDiv.style.opacity = "0";
  48272. this._loadingDiv.style.transition = "opacity 1.5s ease";
  48273. // Loading text
  48274. this._loadingTextDiv = document.createElement("div");
  48275. this._loadingTextDiv.style.position = "absolute";
  48276. this._loadingTextDiv.style.left = "0";
  48277. this._loadingTextDiv.style.top = "50%";
  48278. this._loadingTextDiv.style.marginTop = "80px";
  48279. this._loadingTextDiv.style.width = "100%";
  48280. this._loadingTextDiv.style.height = "20px";
  48281. this._loadingTextDiv.style.fontFamily = "Arial";
  48282. this._loadingTextDiv.style.fontSize = "14px";
  48283. this._loadingTextDiv.style.color = "white";
  48284. this._loadingTextDiv.style.textAlign = "center";
  48285. this._loadingTextDiv.innerHTML = "Loading";
  48286. this._loadingDiv.appendChild(this._loadingTextDiv);
  48287. //set the predefined text
  48288. this._loadingTextDiv.innerHTML = this._loadingText;
  48289. // Generating keyframes
  48290. var style = document.createElement('style');
  48291. style.type = 'text/css';
  48292. 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 }";
  48293. style.innerHTML = keyFrames;
  48294. document.getElementsByTagName('head')[0].appendChild(style);
  48295. // Loading img
  48296. var imgBack = new Image();
  48297. 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";
  48298. imgBack.style.position = "absolute";
  48299. imgBack.style.left = "50%";
  48300. imgBack.style.top = "50%";
  48301. imgBack.style.marginLeft = "-60px";
  48302. imgBack.style.marginTop = "-60px";
  48303. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  48304. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  48305. imgBack.style.transformOrigin = "50% 50%";
  48306. imgBack.style.webkitTransformOrigin = "50% 50%";
  48307. this._loadingDiv.appendChild(imgBack);
  48308. this._resizeLoadingUI();
  48309. window.addEventListener("resize", this._resizeLoadingUI);
  48310. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48311. document.body.appendChild(this._loadingDiv);
  48312. this._loadingDiv.style.opacity = "1";
  48313. };
  48314. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  48315. var _this = this;
  48316. if (!this._loadingDiv) {
  48317. return;
  48318. }
  48319. var onTransitionEnd = function () {
  48320. if (!_this._loadingDiv) {
  48321. return;
  48322. }
  48323. document.body.removeChild(_this._loadingDiv);
  48324. window.removeEventListener("resize", _this._resizeLoadingUI);
  48325. _this._loadingDiv = null;
  48326. };
  48327. this._loadingDiv.style.opacity = "0";
  48328. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  48329. };
  48330. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  48331. set: function (text) {
  48332. this._loadingText = text;
  48333. if (this._loadingTextDiv) {
  48334. this._loadingTextDiv.innerHTML = this._loadingText;
  48335. }
  48336. },
  48337. enumerable: true,
  48338. configurable: true
  48339. });
  48340. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  48341. get: function () {
  48342. return this._loadingDivBackgroundColor;
  48343. },
  48344. set: function (color) {
  48345. this._loadingDivBackgroundColor = color;
  48346. if (!this._loadingDiv) {
  48347. return;
  48348. }
  48349. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48350. },
  48351. enumerable: true,
  48352. configurable: true
  48353. });
  48354. return DefaultLoadingScreen;
  48355. }());
  48356. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  48357. })(BABYLON || (BABYLON = {}));
  48358. //# sourceMappingURL=babylon.loadingScreen.js.map
  48359. var BABYLON;
  48360. (function (BABYLON) {
  48361. var SceneLoader = (function () {
  48362. function SceneLoader() {
  48363. }
  48364. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  48365. get: function () {
  48366. return 0;
  48367. },
  48368. enumerable: true,
  48369. configurable: true
  48370. });
  48371. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  48372. get: function () {
  48373. return 1;
  48374. },
  48375. enumerable: true,
  48376. configurable: true
  48377. });
  48378. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  48379. get: function () {
  48380. return 2;
  48381. },
  48382. enumerable: true,
  48383. configurable: true
  48384. });
  48385. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  48386. get: function () {
  48387. return 3;
  48388. },
  48389. enumerable: true,
  48390. configurable: true
  48391. });
  48392. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  48393. get: function () {
  48394. return SceneLoader._ForceFullSceneLoadingForIncremental;
  48395. },
  48396. set: function (value) {
  48397. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  48398. },
  48399. enumerable: true,
  48400. configurable: true
  48401. });
  48402. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  48403. get: function () {
  48404. return SceneLoader._ShowLoadingScreen;
  48405. },
  48406. set: function (value) {
  48407. SceneLoader._ShowLoadingScreen = value;
  48408. },
  48409. enumerable: true,
  48410. configurable: true
  48411. });
  48412. Object.defineProperty(SceneLoader, "loggingLevel", {
  48413. get: function () {
  48414. return SceneLoader._loggingLevel;
  48415. },
  48416. set: function (value) {
  48417. SceneLoader._loggingLevel = value;
  48418. },
  48419. enumerable: true,
  48420. configurable: true
  48421. });
  48422. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  48423. get: function () {
  48424. return SceneLoader._CleanBoneMatrixWeights;
  48425. },
  48426. set: function (value) {
  48427. SceneLoader._CleanBoneMatrixWeights = value;
  48428. },
  48429. enumerable: true,
  48430. configurable: true
  48431. });
  48432. SceneLoader._getDefaultPlugin = function () {
  48433. return SceneLoader._registeredPlugins[".babylon"];
  48434. };
  48435. SceneLoader._getPluginForExtension = function (extension) {
  48436. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  48437. if (registeredPlugin) {
  48438. return registeredPlugin;
  48439. }
  48440. return SceneLoader._getDefaultPlugin();
  48441. };
  48442. SceneLoader._getPluginForDirectLoad = function (data) {
  48443. for (var extension in SceneLoader._registeredPlugins) {
  48444. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  48445. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  48446. return SceneLoader._registeredPlugins[extension];
  48447. }
  48448. }
  48449. return SceneLoader._getDefaultPlugin();
  48450. };
  48451. SceneLoader._getPluginForFilename = function (sceneFilename) {
  48452. if (sceneFilename.name) {
  48453. sceneFilename = sceneFilename.name;
  48454. }
  48455. var dotPosition = sceneFilename.lastIndexOf(".");
  48456. var queryStringPosition = sceneFilename.indexOf("?");
  48457. if (queryStringPosition === -1) {
  48458. queryStringPosition = sceneFilename.length;
  48459. }
  48460. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  48461. return SceneLoader._getPluginForExtension(extension);
  48462. };
  48463. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  48464. SceneLoader._getDirectLoad = function (sceneFilename) {
  48465. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  48466. return sceneFilename.substr(5);
  48467. }
  48468. return null;
  48469. };
  48470. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48471. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  48472. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  48473. var plugin = registeredPlugin.plugin;
  48474. var useArrayBuffer = registeredPlugin.isBinary;
  48475. var database;
  48476. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  48477. var dataCallback = function (data) {
  48478. if (scene.isDisposed) {
  48479. onError("Scene has been disposed");
  48480. return;
  48481. }
  48482. scene.database = database;
  48483. try {
  48484. onSuccess(plugin, data);
  48485. }
  48486. catch (e) {
  48487. onError(null, e);
  48488. }
  48489. };
  48490. var manifestChecked = function (success) {
  48491. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  48492. onError(request.status + " " + request.statusText);
  48493. });
  48494. };
  48495. if (directLoad) {
  48496. dataCallback(directLoad);
  48497. return;
  48498. }
  48499. if (rootUrl.indexOf("file:") === -1) {
  48500. if (scene.getEngine().enableOfflineSupport) {
  48501. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  48502. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  48503. }
  48504. else {
  48505. manifestChecked(true);
  48506. }
  48507. }
  48508. else {
  48509. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  48510. }
  48511. };
  48512. // Public functions
  48513. SceneLoader.GetPluginForExtension = function (extension) {
  48514. return SceneLoader._getPluginForExtension(extension).plugin;
  48515. };
  48516. SceneLoader.RegisterPlugin = function (plugin) {
  48517. if (typeof plugin.extensions === "string") {
  48518. var extension = plugin.extensions;
  48519. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48520. plugin: plugin,
  48521. isBinary: false
  48522. };
  48523. }
  48524. else {
  48525. var extensions = plugin.extensions;
  48526. Object.keys(extensions).forEach(function (extension) {
  48527. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48528. plugin: plugin,
  48529. isBinary: extensions[extension].isBinary
  48530. };
  48531. });
  48532. }
  48533. };
  48534. /**
  48535. * Import meshes into a scene
  48536. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  48537. * @param rootUrl a string that defines the root url for scene and resources
  48538. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48539. * @param scene the instance of BABYLON.Scene to append to
  48540. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  48541. * @param onProgress a callback with a progress event for each file being loaded
  48542. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48543. */
  48544. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48545. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48546. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48547. return;
  48548. }
  48549. var loadingToken = {};
  48550. scene._addPendingData(loadingToken);
  48551. var errorHandler = function (message, exception) {
  48552. if (onError) {
  48553. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48554. }
  48555. scene._removePendingData(loadingToken);
  48556. };
  48557. var progressHandler = function (event) {
  48558. if (onProgress) {
  48559. onProgress(event);
  48560. }
  48561. };
  48562. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48563. if (plugin.importMesh) {
  48564. var syncedPlugin = plugin;
  48565. var meshes = [];
  48566. var particleSystems = [];
  48567. var skeletons = [];
  48568. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  48569. return;
  48570. }
  48571. if (onSuccess) {
  48572. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48573. onSuccess(meshes, particleSystems, skeletons);
  48574. scene._removePendingData(loadingToken);
  48575. }
  48576. }
  48577. else {
  48578. var asyncedPlugin = plugin;
  48579. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  48580. if (onSuccess) {
  48581. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48582. onSuccess(meshes, particleSystems, skeletons);
  48583. scene._removePendingData(loadingToken);
  48584. }
  48585. }, progressHandler, errorHandler);
  48586. }
  48587. }, progressHandler, errorHandler);
  48588. };
  48589. /**
  48590. * Load a scene
  48591. * @param rootUrl a string that defines the root url for scene and resources
  48592. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48593. * @param engine is the instance of BABYLON.Engine to use to create the scene
  48594. * @param onSuccess a callback with the scene when import succeeds
  48595. * @param onProgress a callback with a progress event for each file being loaded
  48596. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48597. */
  48598. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  48599. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  48600. };
  48601. /**
  48602. * Append a scene
  48603. * @param rootUrl a string that defines the root url for scene and resources
  48604. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48605. * @param scene is the instance of BABYLON.Scene to append to
  48606. * @param onSuccess a callback with the scene when import succeeds
  48607. * @param onProgress a callback with a progress event for each file being loaded
  48608. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48609. */
  48610. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48611. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48612. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48613. return;
  48614. }
  48615. if (SceneLoader.ShowLoadingScreen) {
  48616. scene.getEngine().displayLoadingUI();
  48617. }
  48618. var loadingToken = {};
  48619. scene._addPendingData(loadingToken);
  48620. var errorHandler = function (message, exception) {
  48621. if (onError) {
  48622. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48623. }
  48624. scene._removePendingData(loadingToken);
  48625. scene.getEngine().hideLoadingUI();
  48626. };
  48627. var progressHandler = function (event) {
  48628. if (onProgress) {
  48629. onProgress(event);
  48630. }
  48631. };
  48632. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48633. if (plugin.load) {
  48634. var syncedPlugin = plugin;
  48635. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  48636. return;
  48637. }
  48638. if (onSuccess) {
  48639. onSuccess(scene);
  48640. }
  48641. scene.loadingPluginName = plugin.name;
  48642. scene._removePendingData(loadingToken);
  48643. }
  48644. else {
  48645. var asyncedPlugin = plugin;
  48646. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  48647. if (onSuccess) {
  48648. onSuccess(scene);
  48649. }
  48650. scene.loadingPluginName = plugin.name;
  48651. scene._removePendingData(loadingToken);
  48652. }, progressHandler, errorHandler);
  48653. }
  48654. if (SceneLoader.ShowLoadingScreen) {
  48655. scene.executeWhenReady(function () {
  48656. scene.getEngine().hideLoadingUI();
  48657. });
  48658. }
  48659. }, progressHandler, errorHandler);
  48660. };
  48661. // Flags
  48662. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  48663. SceneLoader._ShowLoadingScreen = true;
  48664. SceneLoader._CleanBoneMatrixWeights = false;
  48665. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  48666. // Members
  48667. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  48668. SceneLoader._registeredPlugins = {};
  48669. return SceneLoader;
  48670. }());
  48671. BABYLON.SceneLoader = SceneLoader;
  48672. ;
  48673. })(BABYLON || (BABYLON = {}));
  48674. //# sourceMappingURL=babylon.sceneLoader.js.map
  48675. var BABYLON;
  48676. (function (BABYLON) {
  48677. var Internals;
  48678. (function (Internals) {
  48679. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  48680. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48681. var parsedMaterial = parsedData.materials[index];
  48682. if (parsedMaterial.id === id) {
  48683. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48684. }
  48685. }
  48686. return null;
  48687. };
  48688. var isDescendantOf = function (mesh, names, hierarchyIds) {
  48689. for (var i in names) {
  48690. if (mesh.name === names[i]) {
  48691. hierarchyIds.push(mesh.id);
  48692. return true;
  48693. }
  48694. }
  48695. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  48696. hierarchyIds.push(mesh.id);
  48697. return true;
  48698. }
  48699. return false;
  48700. };
  48701. var logOperation = function (operation, producer) {
  48702. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  48703. };
  48704. BABYLON.SceneLoader.RegisterPlugin({
  48705. name: "babylon.js",
  48706. extensions: ".babylon",
  48707. canDirectLoad: function (data) {
  48708. if (data.indexOf("babylon") !== -1) {
  48709. return true;
  48710. }
  48711. return false;
  48712. },
  48713. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  48714. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48715. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48716. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48717. // and avoid problems with multiple concurrent .babylon loads.
  48718. var log = "importMesh has failed JSON parse";
  48719. try {
  48720. var parsedData = JSON.parse(data);
  48721. log = "";
  48722. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48723. if (!meshesNames) {
  48724. meshesNames = null;
  48725. }
  48726. else if (!Array.isArray(meshesNames)) {
  48727. meshesNames = [meshesNames];
  48728. }
  48729. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48730. var loadedSkeletonsIds = [];
  48731. var loadedMaterialsIds = [];
  48732. var hierarchyIds = [];
  48733. var index;
  48734. var cache;
  48735. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48736. var parsedMesh = parsedData.meshes[index];
  48737. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  48738. if (meshesNames !== null) {
  48739. // Remove found mesh name from list.
  48740. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  48741. }
  48742. //Geometry?
  48743. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  48744. //does the file contain geometries?
  48745. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  48746. //find the correct geometry and add it to the scene
  48747. var found = false;
  48748. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  48749. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  48750. return;
  48751. }
  48752. else {
  48753. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  48754. if (parsedGeometryData.id === parsedMesh.geometryId) {
  48755. switch (geometryType) {
  48756. case "boxes":
  48757. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  48758. break;
  48759. case "spheres":
  48760. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  48761. break;
  48762. case "cylinders":
  48763. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  48764. break;
  48765. case "toruses":
  48766. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  48767. break;
  48768. case "grounds":
  48769. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  48770. break;
  48771. case "planes":
  48772. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  48773. break;
  48774. case "torusKnots":
  48775. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  48776. break;
  48777. case "vertexData":
  48778. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  48779. break;
  48780. }
  48781. found = true;
  48782. }
  48783. });
  48784. }
  48785. });
  48786. if (found === false) {
  48787. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  48788. }
  48789. }
  48790. }
  48791. // Material ?
  48792. if (parsedMesh.materialId) {
  48793. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  48794. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48795. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  48796. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  48797. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  48798. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  48799. var subMatId = parsedMultiMaterial.materials[matIndex];
  48800. loadedMaterialsIds.push(subMatId);
  48801. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  48802. log += "\n\tMaterial " + mat.toString(fullDetails);
  48803. }
  48804. loadedMaterialsIds.push(parsedMultiMaterial.id);
  48805. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48806. materialFound = true;
  48807. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  48808. break;
  48809. }
  48810. }
  48811. }
  48812. if (materialFound === false) {
  48813. loadedMaterialsIds.push(parsedMesh.materialId);
  48814. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  48815. if (!mat) {
  48816. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  48817. }
  48818. else {
  48819. log += "\n\tMaterial " + mat.toString(fullDetails);
  48820. }
  48821. }
  48822. }
  48823. // Skeleton ?
  48824. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48825. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  48826. if (skeletonAlreadyLoaded === false) {
  48827. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  48828. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  48829. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  48830. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48831. skeletons.push(skeleton);
  48832. loadedSkeletonsIds.push(parsedSkeleton.id);
  48833. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  48834. }
  48835. }
  48836. }
  48837. }
  48838. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48839. meshes.push(mesh);
  48840. log += "\n\tMesh " + mesh.toString(fullDetails);
  48841. }
  48842. }
  48843. // Connecting parents
  48844. var currentMesh;
  48845. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48846. currentMesh = scene.meshes[index];
  48847. if (currentMesh._waitingParentId) {
  48848. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  48849. currentMesh._waitingParentId = undefined;
  48850. }
  48851. }
  48852. // freeze and compute world matrix application
  48853. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48854. currentMesh = scene.meshes[index];
  48855. if (currentMesh._waitingFreezeWorldMatrix) {
  48856. currentMesh.freezeWorldMatrix();
  48857. currentMesh._waitingFreezeWorldMatrix = undefined;
  48858. }
  48859. else {
  48860. currentMesh.computeWorldMatrix(true);
  48861. }
  48862. }
  48863. }
  48864. // Particles
  48865. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48866. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48867. var parsedParticleSystem = parsedData.particleSystems[index];
  48868. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  48869. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  48870. }
  48871. }
  48872. }
  48873. return true;
  48874. }
  48875. catch (err) {
  48876. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  48877. log = null;
  48878. throw err;
  48879. }
  48880. finally {
  48881. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48882. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48883. }
  48884. }
  48885. },
  48886. load: function (scene, data, rootUrl) {
  48887. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48888. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48889. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48890. // and avoid problems with multiple concurrent .babylon loads.
  48891. var log = "importScene has failed JSON parse";
  48892. try {
  48893. var parsedData = JSON.parse(data);
  48894. log = "";
  48895. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48896. // Scene
  48897. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  48898. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  48899. }
  48900. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  48901. scene.autoClear = parsedData.autoClear;
  48902. }
  48903. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  48904. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  48905. }
  48906. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  48907. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  48908. }
  48909. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  48910. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  48911. }
  48912. // Fog
  48913. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  48914. scene.fogMode = parsedData.fogMode;
  48915. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  48916. scene.fogStart = parsedData.fogStart;
  48917. scene.fogEnd = parsedData.fogEnd;
  48918. scene.fogDensity = parsedData.fogDensity;
  48919. log += "\tFog mode for scene: ";
  48920. switch (scene.fogMode) {
  48921. // getters not compiling, so using hardcoded
  48922. case 1:
  48923. log += "exp\n";
  48924. break;
  48925. case 2:
  48926. log += "exp2\n";
  48927. break;
  48928. case 3:
  48929. log += "linear\n";
  48930. break;
  48931. }
  48932. }
  48933. //Physics
  48934. if (parsedData.physicsEnabled) {
  48935. var physicsPlugin;
  48936. if (parsedData.physicsEngine === "cannon") {
  48937. physicsPlugin = new BABYLON.CannonJSPlugin();
  48938. }
  48939. else if (parsedData.physicsEngine === "oimo") {
  48940. physicsPlugin = new BABYLON.OimoJSPlugin();
  48941. }
  48942. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  48943. //else - default engine, which is currently oimo
  48944. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  48945. scene.enablePhysics(physicsGravity, physicsPlugin);
  48946. }
  48947. // Metadata
  48948. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  48949. scene.metadata = parsedData.metadata;
  48950. }
  48951. //collisions, if defined. otherwise, default is true
  48952. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  48953. scene.collisionsEnabled = parsedData.collisionsEnabled;
  48954. }
  48955. scene.workerCollisions = !!parsedData.workerCollisions;
  48956. var index;
  48957. var cache;
  48958. // Lights
  48959. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  48960. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  48961. var parsedLight = parsedData.lights[index];
  48962. var light = BABYLON.Light.Parse(parsedLight, scene);
  48963. log += (index === 0 ? "\n\tLights:" : "");
  48964. log += "\n\t\t" + light.toString(fullDetails);
  48965. }
  48966. }
  48967. // Animations
  48968. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  48969. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  48970. var parsedAnimation = parsedData.animations[index];
  48971. var animation = BABYLON.Animation.Parse(parsedAnimation);
  48972. scene.animations.push(animation);
  48973. log += (index === 0 ? "\n\tAnimations:" : "");
  48974. log += "\n\t\t" + animation.toString(fullDetails);
  48975. }
  48976. }
  48977. if (parsedData.autoAnimate) {
  48978. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  48979. }
  48980. // Materials
  48981. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  48982. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48983. var parsedMaterial = parsedData.materials[index];
  48984. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48985. log += (index === 0 ? "\n\tMaterials:" : "");
  48986. log += "\n\t\t" + mat.toString(fullDetails);
  48987. }
  48988. }
  48989. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48990. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  48991. var parsedMultiMaterial = parsedData.multiMaterials[index];
  48992. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48993. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  48994. log += "\n\t\t" + mmat.toString(fullDetails);
  48995. }
  48996. }
  48997. // Morph targets
  48998. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  48999. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49000. var managerData = _a[_i];
  49001. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49002. }
  49003. }
  49004. // Skeletons
  49005. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49006. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49007. var parsedSkeleton = parsedData.skeletons[index];
  49008. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49009. log += (index === 0 ? "\n\tSkeletons:" : "");
  49010. log += "\n\t\t" + skeleton.toString(fullDetails);
  49011. }
  49012. }
  49013. // Geometries
  49014. var geometries = parsedData.geometries;
  49015. if (geometries !== undefined && geometries !== null) {
  49016. // Boxes
  49017. var boxes = geometries.boxes;
  49018. if (boxes !== undefined && boxes !== null) {
  49019. for (index = 0, cache = boxes.length; index < cache; index++) {
  49020. var parsedBox = boxes[index];
  49021. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49022. }
  49023. }
  49024. // Spheres
  49025. var spheres = geometries.spheres;
  49026. if (spheres !== undefined && spheres !== null) {
  49027. for (index = 0, cache = spheres.length; index < cache; index++) {
  49028. var parsedSphere = spheres[index];
  49029. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49030. }
  49031. }
  49032. // Cylinders
  49033. var cylinders = geometries.cylinders;
  49034. if (cylinders !== undefined && cylinders !== null) {
  49035. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49036. var parsedCylinder = cylinders[index];
  49037. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49038. }
  49039. }
  49040. // Toruses
  49041. var toruses = geometries.toruses;
  49042. if (toruses !== undefined && toruses !== null) {
  49043. for (index = 0, cache = toruses.length; index < cache; index++) {
  49044. var parsedTorus = toruses[index];
  49045. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49046. }
  49047. }
  49048. // Grounds
  49049. var grounds = geometries.grounds;
  49050. if (grounds !== undefined && grounds !== null) {
  49051. for (index = 0, cache = grounds.length; index < cache; index++) {
  49052. var parsedGround = grounds[index];
  49053. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49054. }
  49055. }
  49056. // Planes
  49057. var planes = geometries.planes;
  49058. if (planes !== undefined && planes !== null) {
  49059. for (index = 0, cache = planes.length; index < cache; index++) {
  49060. var parsedPlane = planes[index];
  49061. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49062. }
  49063. }
  49064. // TorusKnots
  49065. var torusKnots = geometries.torusKnots;
  49066. if (torusKnots !== undefined && torusKnots !== null) {
  49067. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49068. var parsedTorusKnot = torusKnots[index];
  49069. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49070. }
  49071. }
  49072. // VertexData
  49073. var vertexData = geometries.vertexData;
  49074. if (vertexData !== undefined && vertexData !== null) {
  49075. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49076. var parsedVertexData = vertexData[index];
  49077. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49078. }
  49079. }
  49080. }
  49081. // Meshes
  49082. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49083. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49084. var parsedMesh = parsedData.meshes[index];
  49085. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49086. log += (index === 0 ? "\n\tMeshes:" : "");
  49087. log += "\n\t\t" + mesh.toString(fullDetails);
  49088. }
  49089. }
  49090. // Cameras
  49091. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49092. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49093. var parsedCamera = parsedData.cameras[index];
  49094. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49095. log += (index === 0 ? "\n\tCameras:" : "");
  49096. log += "\n\t\t" + camera.toString(fullDetails);
  49097. }
  49098. }
  49099. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49100. scene.setActiveCameraByID(parsedData.activeCameraID);
  49101. }
  49102. // Browsing all the graph to connect the dots
  49103. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49104. var camera = scene.cameras[index];
  49105. if (camera._waitingParentId) {
  49106. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49107. camera._waitingParentId = undefined;
  49108. }
  49109. }
  49110. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49111. var light = scene.lights[index];
  49112. if (light._waitingParentId) {
  49113. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49114. light._waitingParentId = undefined;
  49115. }
  49116. }
  49117. // Sounds
  49118. var loadedSounds = [];
  49119. var loadedSound;
  49120. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49121. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49122. var parsedSound = parsedData.sounds[index];
  49123. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49124. if (!parsedSound.url)
  49125. parsedSound.url = parsedSound.name;
  49126. if (!loadedSounds[parsedSound.url]) {
  49127. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49128. loadedSounds[parsedSound.url] = loadedSound;
  49129. }
  49130. else {
  49131. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49132. }
  49133. }
  49134. else {
  49135. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49136. }
  49137. }
  49138. }
  49139. loadedSounds = [];
  49140. // Connect parents & children and parse actions
  49141. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49142. var mesh = scene.meshes[index];
  49143. if (mesh._waitingParentId) {
  49144. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  49145. mesh._waitingParentId = undefined;
  49146. }
  49147. if (mesh._waitingActions) {
  49148. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  49149. mesh._waitingActions = undefined;
  49150. }
  49151. }
  49152. // freeze world matrix application
  49153. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49154. var currentMesh = scene.meshes[index];
  49155. if (currentMesh._waitingFreezeWorldMatrix) {
  49156. currentMesh.freezeWorldMatrix();
  49157. currentMesh._waitingFreezeWorldMatrix = undefined;
  49158. }
  49159. else {
  49160. currentMesh.computeWorldMatrix(true);
  49161. }
  49162. }
  49163. // Particles Systems
  49164. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49165. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49166. var parsedParticleSystem = parsedData.particleSystems[index];
  49167. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  49168. }
  49169. }
  49170. // Lens flares
  49171. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  49172. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  49173. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  49174. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  49175. }
  49176. }
  49177. // Shadows
  49178. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  49179. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  49180. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  49181. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  49182. }
  49183. }
  49184. // Lights exclusions / inclusions
  49185. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49186. var light = scene.lights[index];
  49187. // Excluded check
  49188. if (light._excludedMeshesIds.length > 0) {
  49189. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  49190. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  49191. if (excludedMesh) {
  49192. light.excludedMeshes.push(excludedMesh);
  49193. }
  49194. }
  49195. light._excludedMeshesIds = [];
  49196. }
  49197. // Included check
  49198. if (light._includedOnlyMeshesIds.length > 0) {
  49199. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  49200. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  49201. if (includedOnlyMesh) {
  49202. light.includedOnlyMeshes.push(includedOnlyMesh);
  49203. }
  49204. }
  49205. light._includedOnlyMeshesIds = [];
  49206. }
  49207. }
  49208. // Actions (scene)
  49209. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49210. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49211. }
  49212. // Finish
  49213. return true;
  49214. }
  49215. catch (err) {
  49216. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  49217. log = null;
  49218. throw err;
  49219. }
  49220. finally {
  49221. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49222. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49223. }
  49224. }
  49225. }
  49226. });
  49227. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49228. })(BABYLON || (BABYLON = {}));
  49229. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49230. var BABYLON;
  49231. (function (BABYLON) {
  49232. var FilesInput = (function () {
  49233. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  49234. this.onProcessFileCallback = function () { return true; };
  49235. this._engine = engine;
  49236. this._currentScene = scene;
  49237. this._sceneLoadedCallback = sceneLoadedCallback;
  49238. this._progressCallback = progressCallback;
  49239. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  49240. this._textureLoadingCallback = textureLoadingCallback;
  49241. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  49242. this._onReloadCallback = onReloadCallback;
  49243. }
  49244. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  49245. var _this = this;
  49246. if (elementToMonitor) {
  49247. this._elementToMonitor = elementToMonitor;
  49248. this._dragEnterHandler = function (e) { _this.drag(e); };
  49249. this._dragOverHandler = function (e) { _this.drag(e); };
  49250. this._dropHandler = function (e) { _this.drop(e); };
  49251. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  49252. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  49253. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  49254. }
  49255. };
  49256. FilesInput.prototype.dispose = function () {
  49257. if (!this._elementToMonitor) {
  49258. return;
  49259. }
  49260. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  49261. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  49262. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  49263. };
  49264. FilesInput.prototype.renderFunction = function () {
  49265. if (this._additionalRenderLoopLogicCallback) {
  49266. this._additionalRenderLoopLogicCallback();
  49267. }
  49268. if (this._currentScene) {
  49269. if (this._textureLoadingCallback) {
  49270. var remaining = this._currentScene.getWaitingItemsCount();
  49271. if (remaining > 0) {
  49272. this._textureLoadingCallback(remaining);
  49273. }
  49274. }
  49275. this._currentScene.render();
  49276. }
  49277. };
  49278. FilesInput.prototype.drag = function (e) {
  49279. e.stopPropagation();
  49280. e.preventDefault();
  49281. };
  49282. FilesInput.prototype.drop = function (eventDrop) {
  49283. eventDrop.stopPropagation();
  49284. eventDrop.preventDefault();
  49285. this.loadFiles(eventDrop);
  49286. };
  49287. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  49288. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  49289. reader.readEntries(function (fileEntries) {
  49290. var remaining = fileEntries.length;
  49291. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  49292. var fileEntry = fileEntries_1[_i];
  49293. if (fileEntry.isFile) {
  49294. fileEntry.file(function (file) {
  49295. file.correctName = relativePath + file.name;
  49296. files.push(file);
  49297. remaining--;
  49298. if (remaining === 0) {
  49299. callback();
  49300. }
  49301. });
  49302. }
  49303. else {
  49304. remaining--;
  49305. if (remaining === 0) {
  49306. callback();
  49307. }
  49308. }
  49309. }
  49310. });
  49311. };
  49312. FilesInput.prototype._processFiles = function (files) {
  49313. var skippedFiles = 0;
  49314. for (var i = 0; i < files.length; i++) {
  49315. var name = files[i].correctName.toLowerCase();
  49316. var extension = name.split('.').pop();
  49317. if (!this.onProcessFileCallback(files[i], name, extension)) {
  49318. skippedFiles++;
  49319. continue;
  49320. }
  49321. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  49322. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  49323. this._sceneFileToLoad = files[i];
  49324. }
  49325. else {
  49326. FilesInput.FilesToLoad[name] = files[i];
  49327. }
  49328. }
  49329. if (this._onReloadCallback) {
  49330. this._onReloadCallback(this._sceneFileToLoad);
  49331. }
  49332. else if (skippedFiles < files.length) {
  49333. this.reload();
  49334. }
  49335. };
  49336. FilesInput.prototype.loadFiles = function (event) {
  49337. var _this = this;
  49338. if (this._startingProcessingFilesCallback)
  49339. this._startingProcessingFilesCallback();
  49340. // Handling data transfer via drag'n'drop
  49341. if (event && event.dataTransfer && event.dataTransfer.files) {
  49342. this._filesToLoad = event.dataTransfer.files;
  49343. }
  49344. // Handling files from input files
  49345. if (event && event.target && event.target.files) {
  49346. this._filesToLoad = event.target.files;
  49347. }
  49348. if (this._filesToLoad && this._filesToLoad.length > 0) {
  49349. var files_1 = [];
  49350. var folders = [];
  49351. var items = event.dataTransfer ? event.dataTransfer.items : null;
  49352. for (var i = 0; i < this._filesToLoad.length; i++) {
  49353. var fileToLoad = this._filesToLoad[i];
  49354. var name_1 = fileToLoad.name.toLowerCase();
  49355. var type = fileToLoad.type;
  49356. var entry = void 0;
  49357. fileToLoad.correctName = name_1;
  49358. if (items) {
  49359. var item = items[i];
  49360. if (item.getAsEntry) {
  49361. entry = item.getAsEntry();
  49362. }
  49363. else if (item.webkitGetAsEntry) {
  49364. entry = item.webkitGetAsEntry();
  49365. }
  49366. }
  49367. if (!entry) {
  49368. files_1.push(fileToLoad);
  49369. }
  49370. else {
  49371. if (entry.isDirectory) {
  49372. folders.push(entry);
  49373. }
  49374. else {
  49375. files_1.push(fileToLoad);
  49376. }
  49377. }
  49378. }
  49379. if (folders.length === 0) {
  49380. this._processFiles(files_1);
  49381. }
  49382. else {
  49383. var remaining = folders.length;
  49384. // Extract folder content
  49385. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  49386. var folder = folders_1[_i];
  49387. this._handleFolderDrop(folder, files_1, function () {
  49388. remaining--;
  49389. if (remaining === 0) {
  49390. _this._processFiles(files_1);
  49391. }
  49392. });
  49393. }
  49394. }
  49395. }
  49396. };
  49397. FilesInput.prototype.reload = function () {
  49398. var _this = this;
  49399. // If a ".babylon" file has been provided
  49400. if (this._sceneFileToLoad) {
  49401. if (this._currentScene) {
  49402. if (BABYLON.Tools.errorsCount > 0) {
  49403. BABYLON.Tools.ClearLogCache();
  49404. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  49405. }
  49406. this._engine.stopRenderLoop();
  49407. this._currentScene.dispose();
  49408. }
  49409. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  49410. _this._currentScene = newScene;
  49411. if (_this._sceneLoadedCallback) {
  49412. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  49413. }
  49414. // Wait for textures and shaders to be ready
  49415. _this._currentScene.executeWhenReady(function () {
  49416. _this._engine.runRenderLoop(function () {
  49417. _this.renderFunction();
  49418. });
  49419. });
  49420. }, function (progress) {
  49421. if (_this._progressCallback) {
  49422. _this._progressCallback(progress);
  49423. }
  49424. });
  49425. }
  49426. else {
  49427. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  49428. }
  49429. };
  49430. FilesInput.FilesToLoad = new Array();
  49431. return FilesInput;
  49432. }());
  49433. BABYLON.FilesInput = FilesInput;
  49434. })(BABYLON || (BABYLON = {}));
  49435. //# sourceMappingURL=babylon.filesInput.js.map
  49436. var BABYLON;
  49437. (function (BABYLON) {
  49438. /**
  49439. * This class implement a typical dictionary using a string as key and the generic type T as value.
  49440. * The underlying implementation relies on an associative array to ensure the best performances.
  49441. * The value can be anything including 'null' but except 'undefined'
  49442. */
  49443. var StringDictionary = (function () {
  49444. function StringDictionary() {
  49445. this._count = 0;
  49446. this._data = {};
  49447. }
  49448. /**
  49449. * This will clear this dictionary and copy the content from the 'source' one.
  49450. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  49451. * @param source the dictionary to take the content from and copy to this dictionary
  49452. */
  49453. StringDictionary.prototype.copyFrom = function (source) {
  49454. var _this = this;
  49455. this.clear();
  49456. source.forEach(function (t, v) { return _this.add(t, v); });
  49457. };
  49458. /**
  49459. * Get a value based from its key
  49460. * @param key the given key to get the matching value from
  49461. * @return the value if found, otherwise undefined is returned
  49462. */
  49463. StringDictionary.prototype.get = function (key) {
  49464. var val = this._data[key];
  49465. if (val !== undefined) {
  49466. return val;
  49467. }
  49468. return undefined;
  49469. };
  49470. /**
  49471. * Get a value from its key or add it if it doesn't exist.
  49472. * This method will ensure you that a given key/data will be present in the dictionary.
  49473. * @param key the given key to get the matching value from
  49474. * @param factory the factory that will create the value if the key is not present in the dictionary.
  49475. * The factory will only be invoked if there's no data for the given key.
  49476. * @return the value corresponding to the key.
  49477. */
  49478. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  49479. var val = this.get(key);
  49480. if (val !== undefined) {
  49481. return val;
  49482. }
  49483. val = factory(key);
  49484. if (val) {
  49485. this.add(key, val);
  49486. }
  49487. return val;
  49488. };
  49489. /**
  49490. * Get a value from its key if present in the dictionary otherwise add it
  49491. * @param key the key to get the value from
  49492. * @param val if there's no such key/value pair in the dictionary add it with this value
  49493. * @return the value corresponding to the key
  49494. */
  49495. StringDictionary.prototype.getOrAdd = function (key, val) {
  49496. var curVal = this.get(key);
  49497. if (curVal !== undefined) {
  49498. return curVal;
  49499. }
  49500. this.add(key, val);
  49501. return val;
  49502. };
  49503. /**
  49504. * Check if there's a given key in the dictionary
  49505. * @param key the key to check for
  49506. * @return true if the key is present, false otherwise
  49507. */
  49508. StringDictionary.prototype.contains = function (key) {
  49509. return this._data[key] !== undefined;
  49510. };
  49511. /**
  49512. * Add a new key and its corresponding value
  49513. * @param key the key to add
  49514. * @param value the value corresponding to the key
  49515. * @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
  49516. */
  49517. StringDictionary.prototype.add = function (key, value) {
  49518. if (this._data[key] !== undefined) {
  49519. return false;
  49520. }
  49521. this._data[key] = value;
  49522. ++this._count;
  49523. return true;
  49524. };
  49525. StringDictionary.prototype.set = function (key, value) {
  49526. if (this._data[key] === undefined) {
  49527. return false;
  49528. }
  49529. this._data[key] = value;
  49530. return true;
  49531. };
  49532. /**
  49533. * Get the element of the given key and remove it from the dictionary
  49534. * @param key
  49535. */
  49536. StringDictionary.prototype.getAndRemove = function (key) {
  49537. var val = this.get(key);
  49538. if (val !== undefined) {
  49539. delete this._data[key];
  49540. --this._count;
  49541. return val;
  49542. }
  49543. return null;
  49544. };
  49545. /**
  49546. * Remove a key/value from the dictionary.
  49547. * @param key the key to remove
  49548. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  49549. */
  49550. StringDictionary.prototype.remove = function (key) {
  49551. if (this.contains(key)) {
  49552. delete this._data[key];
  49553. --this._count;
  49554. return true;
  49555. }
  49556. return false;
  49557. };
  49558. /**
  49559. * Clear the whole content of the dictionary
  49560. */
  49561. StringDictionary.prototype.clear = function () {
  49562. this._data = {};
  49563. this._count = 0;
  49564. };
  49565. Object.defineProperty(StringDictionary.prototype, "count", {
  49566. get: function () {
  49567. return this._count;
  49568. },
  49569. enumerable: true,
  49570. configurable: true
  49571. });
  49572. /**
  49573. * Execute a callback on each key/val of the dictionary.
  49574. * Note that you can remove any element in this dictionary in the callback implementation
  49575. * @param callback the callback to execute on a given key/value pair
  49576. */
  49577. StringDictionary.prototype.forEach = function (callback) {
  49578. for (var cur in this._data) {
  49579. var val = this._data[cur];
  49580. callback(cur, val);
  49581. }
  49582. };
  49583. /**
  49584. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  49585. * If the callback returns null or undefined the method will iterate to the next key/value pair
  49586. * Note that you can remove any element in this dictionary in the callback implementation
  49587. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  49588. */
  49589. StringDictionary.prototype.first = function (callback) {
  49590. for (var cur in this._data) {
  49591. var val = this._data[cur];
  49592. var res = callback(cur, val);
  49593. if (res) {
  49594. return res;
  49595. }
  49596. }
  49597. return null;
  49598. };
  49599. return StringDictionary;
  49600. }());
  49601. BABYLON.StringDictionary = StringDictionary;
  49602. })(BABYLON || (BABYLON = {}));
  49603. //# sourceMappingURL=babylon.stringDictionary.js.map
  49604. var BABYLON;
  49605. (function (BABYLON) {
  49606. var Tags = (function () {
  49607. function Tags() {
  49608. }
  49609. Tags.EnableFor = function (obj) {
  49610. obj._tags = obj._tags || {};
  49611. obj.hasTags = function () {
  49612. return Tags.HasTags(obj);
  49613. };
  49614. obj.addTags = function (tagsString) {
  49615. return Tags.AddTagsTo(obj, tagsString);
  49616. };
  49617. obj.removeTags = function (tagsString) {
  49618. return Tags.RemoveTagsFrom(obj, tagsString);
  49619. };
  49620. obj.matchesTagsQuery = function (tagsQuery) {
  49621. return Tags.MatchesQuery(obj, tagsQuery);
  49622. };
  49623. };
  49624. Tags.DisableFor = function (obj) {
  49625. delete obj._tags;
  49626. delete obj.hasTags;
  49627. delete obj.addTags;
  49628. delete obj.removeTags;
  49629. delete obj.matchesTagsQuery;
  49630. };
  49631. Tags.HasTags = function (obj) {
  49632. if (!obj._tags) {
  49633. return false;
  49634. }
  49635. return !BABYLON.Tools.IsEmpty(obj._tags);
  49636. };
  49637. Tags.GetTags = function (obj, asString) {
  49638. if (asString === void 0) { asString = true; }
  49639. if (!obj._tags) {
  49640. return null;
  49641. }
  49642. if (asString) {
  49643. var tagsArray = [];
  49644. for (var tag in obj._tags) {
  49645. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  49646. tagsArray.push(tag);
  49647. }
  49648. }
  49649. return tagsArray.join(" ");
  49650. }
  49651. else {
  49652. return obj._tags;
  49653. }
  49654. };
  49655. // the tags 'true' and 'false' are reserved and cannot be used as tags
  49656. // a tag cannot start with '||', '&&', and '!'
  49657. // it cannot contain whitespaces
  49658. Tags.AddTagsTo = function (obj, tagsString) {
  49659. if (!tagsString) {
  49660. return;
  49661. }
  49662. if (typeof tagsString !== "string") {
  49663. return;
  49664. }
  49665. var tags = tagsString.split(" ");
  49666. tags.forEach(function (tag, index, array) {
  49667. Tags._AddTagTo(obj, tag);
  49668. });
  49669. };
  49670. Tags._AddTagTo = function (obj, tag) {
  49671. tag = tag.trim();
  49672. if (tag === "" || tag === "true" || tag === "false") {
  49673. return;
  49674. }
  49675. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  49676. return;
  49677. }
  49678. Tags.EnableFor(obj);
  49679. obj._tags[tag] = true;
  49680. };
  49681. Tags.RemoveTagsFrom = function (obj, tagsString) {
  49682. if (!Tags.HasTags(obj)) {
  49683. return;
  49684. }
  49685. var tags = tagsString.split(" ");
  49686. for (var t in tags) {
  49687. Tags._RemoveTagFrom(obj, tags[t]);
  49688. }
  49689. };
  49690. Tags._RemoveTagFrom = function (obj, tag) {
  49691. delete obj._tags[tag];
  49692. };
  49693. Tags.MatchesQuery = function (obj, tagsQuery) {
  49694. if (tagsQuery === undefined) {
  49695. return true;
  49696. }
  49697. if (tagsQuery === "") {
  49698. return Tags.HasTags(obj);
  49699. }
  49700. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  49701. };
  49702. return Tags;
  49703. }());
  49704. BABYLON.Tags = Tags;
  49705. })(BABYLON || (BABYLON = {}));
  49706. //# sourceMappingURL=babylon.tags.js.map
  49707. var BABYLON;
  49708. (function (BABYLON) {
  49709. var Internals;
  49710. (function (Internals) {
  49711. var AndOrNotEvaluator = (function () {
  49712. function AndOrNotEvaluator() {
  49713. }
  49714. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  49715. if (!query.match(/\([^\(\)]*\)/g)) {
  49716. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  49717. }
  49718. else {
  49719. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  49720. // remove parenthesis
  49721. r = r.slice(1, r.length - 1);
  49722. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  49723. });
  49724. }
  49725. if (query === "true") {
  49726. return true;
  49727. }
  49728. if (query === "false") {
  49729. return false;
  49730. }
  49731. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  49732. };
  49733. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  49734. evaluateCallback = evaluateCallback || (function (r) {
  49735. return r === "true" ? true : false;
  49736. });
  49737. var result;
  49738. var or = parenthesisContent.split("||");
  49739. for (var i in or) {
  49740. if (or.hasOwnProperty(i)) {
  49741. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  49742. var and = ori.split("&&");
  49743. if (and.length > 1) {
  49744. for (var j = 0; j < and.length; ++j) {
  49745. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  49746. if (andj !== "true" && andj !== "false") {
  49747. if (andj[0] === "!") {
  49748. result = !evaluateCallback(andj.substring(1));
  49749. }
  49750. else {
  49751. result = evaluateCallback(andj);
  49752. }
  49753. }
  49754. else {
  49755. result = andj === "true" ? true : false;
  49756. }
  49757. if (!result) {
  49758. ori = "false";
  49759. break;
  49760. }
  49761. }
  49762. }
  49763. if (result || ori === "true") {
  49764. result = true;
  49765. break;
  49766. }
  49767. // result equals false (or undefined)
  49768. if (ori !== "true" && ori !== "false") {
  49769. if (ori[0] === "!") {
  49770. result = !evaluateCallback(ori.substring(1));
  49771. }
  49772. else {
  49773. result = evaluateCallback(ori);
  49774. }
  49775. }
  49776. else {
  49777. result = ori === "true" ? true : false;
  49778. }
  49779. }
  49780. }
  49781. // the whole parenthesis scope is replaced by 'true' or 'false'
  49782. return result ? "true" : "false";
  49783. };
  49784. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  49785. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  49786. // remove whitespaces
  49787. r = r.replace(/[\s]/g, function () { return ""; });
  49788. return r.length % 2 ? "!" : "";
  49789. });
  49790. booleanString = booleanString.trim();
  49791. if (booleanString === "!true") {
  49792. booleanString = "false";
  49793. }
  49794. else if (booleanString === "!false") {
  49795. booleanString = "true";
  49796. }
  49797. return booleanString;
  49798. };
  49799. return AndOrNotEvaluator;
  49800. }());
  49801. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  49802. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49803. })(BABYLON || (BABYLON = {}));
  49804. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  49805. var BABYLON;
  49806. (function (BABYLON) {
  49807. var Database = (function () {
  49808. function Database(urlToScene, callbackManifestChecked) {
  49809. // Handling various flavors of prefixed version of IndexedDB
  49810. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  49811. this.callbackManifestChecked = callbackManifestChecked;
  49812. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  49813. this.db = null;
  49814. this.enableSceneOffline = false;
  49815. this.enableTexturesOffline = false;
  49816. this.manifestVersionFound = 0;
  49817. this.mustUpdateRessources = false;
  49818. this.hasReachedQuota = false;
  49819. if (!Database.IDBStorageEnabled) {
  49820. this.callbackManifestChecked(true);
  49821. }
  49822. else {
  49823. this.checkManifestFile();
  49824. }
  49825. }
  49826. Database.prototype.checkManifestFile = function () {
  49827. var _this = this;
  49828. function noManifestFile() {
  49829. that.enableSceneOffline = false;
  49830. that.enableTexturesOffline = false;
  49831. that.callbackManifestChecked(false);
  49832. }
  49833. var that = this;
  49834. var timeStampUsed = false;
  49835. var manifestURL = this.currentSceneUrl + ".manifest";
  49836. var xhr = new XMLHttpRequest();
  49837. if (navigator.onLine) {
  49838. // Adding a timestamp to by-pass browsers' cache
  49839. timeStampUsed = true;
  49840. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  49841. }
  49842. xhr.open("GET", manifestURL, true);
  49843. xhr.addEventListener("load", function () {
  49844. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  49845. try {
  49846. var manifestFile = JSON.parse(xhr.response);
  49847. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  49848. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  49849. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  49850. _this.manifestVersionFound = manifestFile.version;
  49851. }
  49852. if (_this.callbackManifestChecked) {
  49853. _this.callbackManifestChecked(true);
  49854. }
  49855. }
  49856. catch (ex) {
  49857. noManifestFile();
  49858. }
  49859. }
  49860. else {
  49861. noManifestFile();
  49862. }
  49863. }, false);
  49864. xhr.addEventListener("error", function (event) {
  49865. if (timeStampUsed) {
  49866. timeStampUsed = false;
  49867. // Let's retry without the timeStamp
  49868. // It could fail when coupled with HTML5 Offline API
  49869. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  49870. xhr.open("GET", retryManifestURL, true);
  49871. xhr.send();
  49872. }
  49873. else {
  49874. noManifestFile();
  49875. }
  49876. }, false);
  49877. try {
  49878. xhr.send();
  49879. }
  49880. catch (ex) {
  49881. BABYLON.Tools.Error("Error on XHR send request.");
  49882. that.callbackManifestChecked(false);
  49883. }
  49884. };
  49885. Database.prototype.openAsync = function (successCallback, errorCallback) {
  49886. var _this = this;
  49887. function handleError() {
  49888. that.isSupported = false;
  49889. if (errorCallback)
  49890. errorCallback();
  49891. }
  49892. var that = this;
  49893. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  49894. // Your browser doesn't support IndexedDB
  49895. this.isSupported = false;
  49896. if (errorCallback)
  49897. errorCallback();
  49898. }
  49899. else {
  49900. // If the DB hasn't been opened or created yet
  49901. if (!this.db) {
  49902. this.hasReachedQuota = false;
  49903. this.isSupported = true;
  49904. var request = this.idbFactory.open("babylonjs", 1);
  49905. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  49906. request.onerror = function (event) {
  49907. handleError();
  49908. };
  49909. // executes when a version change transaction cannot complete due to other active transactions
  49910. request.onblocked = function (event) {
  49911. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  49912. handleError();
  49913. };
  49914. // DB has been opened successfully
  49915. request.onsuccess = function (event) {
  49916. _this.db = request.result;
  49917. successCallback();
  49918. };
  49919. // Initialization of the DB. Creating Scenes & Textures stores
  49920. request.onupgradeneeded = function (event) {
  49921. _this.db = (event.target).result;
  49922. try {
  49923. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  49924. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  49925. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  49926. }
  49927. catch (ex) {
  49928. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  49929. handleError();
  49930. }
  49931. };
  49932. }
  49933. else {
  49934. if (successCallback)
  49935. successCallback();
  49936. }
  49937. }
  49938. };
  49939. Database.prototype.loadImageFromDB = function (url, image) {
  49940. var _this = this;
  49941. var completeURL = Database.ReturnFullUrlLocation(url);
  49942. var saveAndLoadImage = function () {
  49943. if (!_this.hasReachedQuota && _this.db !== null) {
  49944. // the texture is not yet in the DB, let's try to save it
  49945. _this._saveImageIntoDBAsync(completeURL, image);
  49946. }
  49947. else {
  49948. image.src = url;
  49949. }
  49950. };
  49951. if (!this.mustUpdateRessources) {
  49952. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  49953. }
  49954. else {
  49955. saveAndLoadImage();
  49956. }
  49957. };
  49958. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  49959. if (this.isSupported && this.db !== null) {
  49960. var texture;
  49961. var transaction = this.db.transaction(["textures"]);
  49962. transaction.onabort = function (event) {
  49963. image.src = url;
  49964. };
  49965. transaction.oncomplete = function (event) {
  49966. var blobTextureURL;
  49967. if (texture) {
  49968. var URL = window.URL || window.webkitURL;
  49969. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  49970. image.onerror = function () {
  49971. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  49972. image.src = url;
  49973. };
  49974. image.src = blobTextureURL;
  49975. }
  49976. else {
  49977. notInDBCallback();
  49978. }
  49979. };
  49980. var getRequest = transaction.objectStore("textures").get(url);
  49981. getRequest.onsuccess = function (event) {
  49982. texture = (event.target).result;
  49983. };
  49984. getRequest.onerror = function (event) {
  49985. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  49986. image.src = url;
  49987. };
  49988. }
  49989. else {
  49990. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49991. image.src = url;
  49992. }
  49993. };
  49994. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  49995. var _this = this;
  49996. if (this.isSupported) {
  49997. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  49998. var generateBlobUrl = function () {
  49999. var blobTextureURL;
  50000. if (blob) {
  50001. var URL = window.URL || window.webkitURL;
  50002. try {
  50003. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  50004. }
  50005. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  50006. catch (ex) {
  50007. blobTextureURL = URL.createObjectURL(blob);
  50008. }
  50009. }
  50010. image.src = blobTextureURL;
  50011. };
  50012. if (Database.IsUASupportingBlobStorage) {
  50013. var xhr = new XMLHttpRequest(), blob;
  50014. xhr.open("GET", url, true);
  50015. xhr.responseType = "blob";
  50016. xhr.addEventListener("load", function () {
  50017. if (xhr.status === 200) {
  50018. // Blob as response (XHR2)
  50019. blob = xhr.response;
  50020. var transaction = _this.db.transaction(["textures"], "readwrite");
  50021. // the transaction could abort because of a QuotaExceededError error
  50022. transaction.onabort = function (event) {
  50023. try {
  50024. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  50025. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50026. _this.hasReachedQuota = true;
  50027. }
  50028. }
  50029. catch (ex) { }
  50030. generateBlobUrl();
  50031. };
  50032. transaction.oncomplete = function (event) {
  50033. generateBlobUrl();
  50034. };
  50035. var newTexture = { textureUrl: url, data: blob };
  50036. try {
  50037. // Put the blob into the dabase
  50038. var addRequest = transaction.objectStore("textures").put(newTexture);
  50039. addRequest.onsuccess = function (event) {
  50040. };
  50041. addRequest.onerror = function (event) {
  50042. generateBlobUrl();
  50043. };
  50044. }
  50045. catch (ex) {
  50046. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  50047. if (ex.code === 25) {
  50048. Database.IsUASupportingBlobStorage = false;
  50049. }
  50050. image.src = url;
  50051. }
  50052. }
  50053. else {
  50054. image.src = url;
  50055. }
  50056. }, false);
  50057. xhr.addEventListener("error", function (event) {
  50058. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  50059. image.src = url;
  50060. }, false);
  50061. xhr.send();
  50062. }
  50063. else {
  50064. image.src = url;
  50065. }
  50066. }
  50067. else {
  50068. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50069. image.src = url;
  50070. }
  50071. };
  50072. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  50073. var _this = this;
  50074. var updateVersion = function (event) {
  50075. // the version is not yet in the DB or we need to update it
  50076. _this._saveVersionIntoDBAsync(url, versionLoaded);
  50077. };
  50078. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  50079. };
  50080. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  50081. var _this = this;
  50082. if (this.isSupported) {
  50083. var version;
  50084. try {
  50085. var transaction = this.db.transaction(["versions"]);
  50086. transaction.oncomplete = function (event) {
  50087. if (version) {
  50088. // If the version in the JSON file is > than the version in DB
  50089. if (_this.manifestVersionFound > version.data) {
  50090. _this.mustUpdateRessources = true;
  50091. updateInDBCallback();
  50092. }
  50093. else {
  50094. callback(version.data);
  50095. }
  50096. }
  50097. else {
  50098. _this.mustUpdateRessources = true;
  50099. updateInDBCallback();
  50100. }
  50101. };
  50102. transaction.onabort = function (event) {
  50103. callback(-1);
  50104. };
  50105. var getRequest = transaction.objectStore("versions").get(url);
  50106. getRequest.onsuccess = function (event) {
  50107. version = (event.target).result;
  50108. };
  50109. getRequest.onerror = function (event) {
  50110. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  50111. callback(-1);
  50112. };
  50113. }
  50114. catch (ex) {
  50115. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  50116. callback(-1);
  50117. }
  50118. }
  50119. else {
  50120. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50121. callback(-1);
  50122. }
  50123. };
  50124. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  50125. var _this = this;
  50126. if (this.isSupported && !this.hasReachedQuota) {
  50127. try {
  50128. // Open a transaction to the database
  50129. var transaction = this.db.transaction(["versions"], "readwrite");
  50130. // the transaction could abort because of a QuotaExceededError error
  50131. transaction.onabort = function (event) {
  50132. try {
  50133. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50134. _this.hasReachedQuota = true;
  50135. }
  50136. }
  50137. catch (ex) { }
  50138. callback(-1);
  50139. };
  50140. transaction.oncomplete = function (event) {
  50141. callback(_this.manifestVersionFound);
  50142. };
  50143. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  50144. // Put the scene into the database
  50145. var addRequest = transaction.objectStore("versions").put(newVersion);
  50146. addRequest.onsuccess = function (event) {
  50147. };
  50148. addRequest.onerror = function (event) {
  50149. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  50150. };
  50151. }
  50152. catch (ex) {
  50153. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  50154. callback(-1);
  50155. }
  50156. }
  50157. else {
  50158. callback(-1);
  50159. }
  50160. };
  50161. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  50162. var _this = this;
  50163. var completeUrl = Database.ReturnFullUrlLocation(url);
  50164. var saveAndLoadFile = function (event) {
  50165. // the scene is not yet in the DB, let's try to save it
  50166. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  50167. };
  50168. this._checkVersionFromDB(completeUrl, function (version) {
  50169. if (version !== -1) {
  50170. if (!_this.mustUpdateRessources) {
  50171. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  50172. }
  50173. else {
  50174. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  50175. }
  50176. }
  50177. else {
  50178. errorCallback();
  50179. }
  50180. });
  50181. };
  50182. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  50183. if (this.isSupported) {
  50184. var targetStore;
  50185. if (url.indexOf(".babylon") !== -1) {
  50186. targetStore = "scenes";
  50187. }
  50188. else {
  50189. targetStore = "textures";
  50190. }
  50191. var file;
  50192. var transaction = this.db.transaction([targetStore]);
  50193. transaction.oncomplete = function (event) {
  50194. if (file) {
  50195. callback(file.data);
  50196. }
  50197. else {
  50198. notInDBCallback();
  50199. }
  50200. };
  50201. transaction.onabort = function (event) {
  50202. notInDBCallback();
  50203. };
  50204. var getRequest = transaction.objectStore(targetStore).get(url);
  50205. getRequest.onsuccess = function (event) {
  50206. file = (event.target).result;
  50207. };
  50208. getRequest.onerror = function (event) {
  50209. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  50210. notInDBCallback();
  50211. };
  50212. }
  50213. else {
  50214. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50215. callback();
  50216. }
  50217. };
  50218. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  50219. var _this = this;
  50220. if (this.isSupported) {
  50221. var targetStore;
  50222. if (url.indexOf(".babylon") !== -1) {
  50223. targetStore = "scenes";
  50224. }
  50225. else {
  50226. targetStore = "textures";
  50227. }
  50228. // Create XHR
  50229. var xhr = new XMLHttpRequest(), fileData;
  50230. xhr.open("GET", url, true);
  50231. if (useArrayBuffer) {
  50232. xhr.responseType = "arraybuffer";
  50233. }
  50234. xhr.onprogress = progressCallback;
  50235. xhr.addEventListener("load", function () {
  50236. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  50237. // Blob as response (XHR2)
  50238. //fileData = xhr.responseText;
  50239. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  50240. if (!_this.hasReachedQuota) {
  50241. // Open a transaction to the database
  50242. var transaction = _this.db.transaction([targetStore], "readwrite");
  50243. // the transaction could abort because of a QuotaExceededError error
  50244. transaction.onabort = function (event) {
  50245. try {
  50246. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  50247. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50248. _this.hasReachedQuota = true;
  50249. }
  50250. }
  50251. catch (ex) { }
  50252. callback(fileData);
  50253. };
  50254. transaction.oncomplete = function (event) {
  50255. callback(fileData);
  50256. };
  50257. var newFile;
  50258. if (targetStore === "scenes") {
  50259. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  50260. }
  50261. else {
  50262. newFile = { textureUrl: url, data: fileData };
  50263. }
  50264. try {
  50265. // Put the scene into the database
  50266. var addRequest = transaction.objectStore(targetStore).put(newFile);
  50267. addRequest.onsuccess = function (event) {
  50268. };
  50269. addRequest.onerror = function (event) {
  50270. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  50271. };
  50272. }
  50273. catch (ex) {
  50274. callback(fileData);
  50275. }
  50276. }
  50277. else {
  50278. callback(fileData);
  50279. }
  50280. }
  50281. else {
  50282. callback();
  50283. }
  50284. }, false);
  50285. xhr.addEventListener("error", function (event) {
  50286. BABYLON.Tools.Error("error on XHR request.");
  50287. callback();
  50288. }, false);
  50289. xhr.send();
  50290. }
  50291. else {
  50292. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50293. callback();
  50294. }
  50295. };
  50296. Database.IsUASupportingBlobStorage = true;
  50297. Database.IDBStorageEnabled = true;
  50298. Database.parseURL = function (url) {
  50299. var a = document.createElement('a');
  50300. a.href = url;
  50301. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  50302. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  50303. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  50304. return absLocation;
  50305. };
  50306. Database.ReturnFullUrlLocation = function (url) {
  50307. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  50308. return (Database.parseURL(window.location.href) + url);
  50309. }
  50310. else {
  50311. return url;
  50312. }
  50313. };
  50314. return Database;
  50315. }());
  50316. BABYLON.Database = Database;
  50317. })(BABYLON || (BABYLON = {}));
  50318. //# sourceMappingURL=babylon.database.js.map
  50319. var BABYLON;
  50320. (function (BABYLON) {
  50321. var FresnelParameters = (function () {
  50322. function FresnelParameters() {
  50323. this._isEnabled = true;
  50324. this.leftColor = BABYLON.Color3.White();
  50325. this.rightColor = BABYLON.Color3.Black();
  50326. this.bias = 0;
  50327. this.power = 1;
  50328. }
  50329. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  50330. get: function () {
  50331. return this._isEnabled;
  50332. },
  50333. set: function (value) {
  50334. if (this._isEnabled === value) {
  50335. return;
  50336. }
  50337. this._isEnabled = value;
  50338. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  50339. },
  50340. enumerable: true,
  50341. configurable: true
  50342. });
  50343. FresnelParameters.prototype.clone = function () {
  50344. var newFresnelParameters = new FresnelParameters();
  50345. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  50346. return newFresnelParameters;
  50347. };
  50348. FresnelParameters.prototype.serialize = function () {
  50349. var serializationObject = {};
  50350. serializationObject.isEnabled = this.isEnabled;
  50351. serializationObject.leftColor = this.leftColor;
  50352. serializationObject.rightColor = this.rightColor;
  50353. serializationObject.bias = this.bias;
  50354. serializationObject.power = this.power;
  50355. return serializationObject;
  50356. };
  50357. FresnelParameters.Parse = function (parsedFresnelParameters) {
  50358. var fresnelParameters = new FresnelParameters();
  50359. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  50360. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  50361. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  50362. fresnelParameters.bias = parsedFresnelParameters.bias;
  50363. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  50364. return fresnelParameters;
  50365. };
  50366. return FresnelParameters;
  50367. }());
  50368. BABYLON.FresnelParameters = FresnelParameters;
  50369. })(BABYLON || (BABYLON = {}));
  50370. //# sourceMappingURL=babylon.fresnelParameters.js.map
  50371. var BABYLON;
  50372. (function (BABYLON) {
  50373. var MultiMaterial = (function (_super) {
  50374. __extends(MultiMaterial, _super);
  50375. function MultiMaterial(name, scene) {
  50376. var _this = _super.call(this, name, scene, true) || this;
  50377. scene.multiMaterials.push(_this);
  50378. _this.subMaterials = new Array();
  50379. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  50380. return _this;
  50381. }
  50382. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  50383. get: function () {
  50384. return this._subMaterials;
  50385. },
  50386. set: function (value) {
  50387. this._subMaterials = value;
  50388. this._hookArray(value);
  50389. },
  50390. enumerable: true,
  50391. configurable: true
  50392. });
  50393. MultiMaterial.prototype._hookArray = function (array) {
  50394. var _this = this;
  50395. var oldPush = array.push;
  50396. array.push = function () {
  50397. var items = [];
  50398. for (var _i = 0; _i < arguments.length; _i++) {
  50399. items[_i] = arguments[_i];
  50400. }
  50401. var result = oldPush.apply(array, items);
  50402. _this._markAllSubMeshesAsTexturesDirty();
  50403. return result;
  50404. };
  50405. var oldSplice = array.splice;
  50406. array.splice = function (index, deleteCount) {
  50407. var deleted = oldSplice.apply(array, [index, deleteCount]);
  50408. _this._markAllSubMeshesAsTexturesDirty();
  50409. return deleted;
  50410. };
  50411. };
  50412. // Properties
  50413. MultiMaterial.prototype.getSubMaterial = function (index) {
  50414. if (index < 0 || index >= this.subMaterials.length) {
  50415. return this.getScene().defaultMaterial;
  50416. }
  50417. return this.subMaterials[index];
  50418. };
  50419. MultiMaterial.prototype.getActiveTextures = function () {
  50420. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  50421. var _a;
  50422. };
  50423. // Methods
  50424. MultiMaterial.prototype.getClassName = function () {
  50425. return "MultiMaterial";
  50426. };
  50427. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  50428. for (var index = 0; index < this.subMaterials.length; index++) {
  50429. var subMaterial = this.subMaterials[index];
  50430. if (subMaterial) {
  50431. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  50432. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  50433. return false;
  50434. }
  50435. continue;
  50436. }
  50437. if (!this.subMaterials[index].isReady(mesh)) {
  50438. return false;
  50439. }
  50440. }
  50441. }
  50442. return true;
  50443. };
  50444. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  50445. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  50446. for (var index = 0; index < this.subMaterials.length; index++) {
  50447. var subMaterial = null;
  50448. if (cloneChildren) {
  50449. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  50450. }
  50451. else {
  50452. subMaterial = this.subMaterials[index];
  50453. }
  50454. newMultiMaterial.subMaterials.push(subMaterial);
  50455. }
  50456. return newMultiMaterial;
  50457. };
  50458. MultiMaterial.prototype.serialize = function () {
  50459. var serializationObject = {};
  50460. serializationObject.name = this.name;
  50461. serializationObject.id = this.id;
  50462. serializationObject.tags = BABYLON.Tags.GetTags(this);
  50463. serializationObject.materials = [];
  50464. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  50465. var subMat = this.subMaterials[matIndex];
  50466. if (subMat) {
  50467. serializationObject.materials.push(subMat.id);
  50468. }
  50469. else {
  50470. serializationObject.materials.push(null);
  50471. }
  50472. }
  50473. return serializationObject;
  50474. };
  50475. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50476. var scene = this.getScene();
  50477. if (!scene) {
  50478. return;
  50479. }
  50480. var index = scene.multiMaterials.indexOf(this);
  50481. if (index >= 0) {
  50482. scene.multiMaterials.splice(index, 1);
  50483. }
  50484. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50485. };
  50486. return MultiMaterial;
  50487. }(BABYLON.Material));
  50488. BABYLON.MultiMaterial = MultiMaterial;
  50489. })(BABYLON || (BABYLON = {}));
  50490. //# sourceMappingURL=babylon.multiMaterial.js.map
  50491. var BABYLON;
  50492. (function (BABYLON) {
  50493. var FreeCameraTouchInput = (function () {
  50494. function FreeCameraTouchInput() {
  50495. this._offsetX = null;
  50496. this._offsetY = null;
  50497. this._pointerCount = 0;
  50498. this._pointerPressed = [];
  50499. this.touchAngularSensibility = 200000.0;
  50500. this.touchMoveSensibility = 250.0;
  50501. }
  50502. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  50503. var _this = this;
  50504. var previousPosition;
  50505. if (this._pointerInput === undefined) {
  50506. this._onLostFocus = function (evt) {
  50507. _this._offsetX = null;
  50508. _this._offsetY = null;
  50509. };
  50510. this._pointerInput = function (p, s) {
  50511. var evt = p.event;
  50512. if (evt.pointerType === "mouse") {
  50513. return;
  50514. }
  50515. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50516. if (!noPreventDefault) {
  50517. evt.preventDefault();
  50518. }
  50519. _this._pointerPressed.push(evt.pointerId);
  50520. if (_this._pointerPressed.length !== 1) {
  50521. return;
  50522. }
  50523. previousPosition = {
  50524. x: evt.clientX,
  50525. y: evt.clientY
  50526. };
  50527. }
  50528. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  50529. if (!noPreventDefault) {
  50530. evt.preventDefault();
  50531. }
  50532. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50533. if (index === -1) {
  50534. return;
  50535. }
  50536. _this._pointerPressed.splice(index, 1);
  50537. if (index != 0) {
  50538. return;
  50539. }
  50540. previousPosition = null;
  50541. _this._offsetX = null;
  50542. _this._offsetY = null;
  50543. }
  50544. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50545. if (!noPreventDefault) {
  50546. evt.preventDefault();
  50547. }
  50548. if (!previousPosition) {
  50549. return;
  50550. }
  50551. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50552. if (index != 0) {
  50553. return;
  50554. }
  50555. _this._offsetX = evt.clientX - previousPosition.x;
  50556. _this._offsetY = -(evt.clientY - previousPosition.y);
  50557. }
  50558. };
  50559. }
  50560. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  50561. element.addEventListener("blur", this._onLostFocus);
  50562. };
  50563. FreeCameraTouchInput.prototype.detachControl = function (element) {
  50564. if (this._pointerInput && element) {
  50565. this.camera.getScene().onPointerObservable.remove(this._observer);
  50566. this._observer = null;
  50567. element.removeEventListener("blur", this._onLostFocus);
  50568. this._onLostFocus = null;
  50569. this._pointerPressed = [];
  50570. this._offsetX = null;
  50571. this._offsetY = null;
  50572. this._pointerCount = 0;
  50573. }
  50574. };
  50575. FreeCameraTouchInput.prototype.checkInputs = function () {
  50576. if (this._offsetX) {
  50577. var camera = this.camera;
  50578. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  50579. if (this._pointerPressed.length > 1) {
  50580. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  50581. }
  50582. else {
  50583. var speed = camera._computeLocalCameraSpeed();
  50584. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  50585. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  50586. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  50587. }
  50588. }
  50589. };
  50590. FreeCameraTouchInput.prototype.getClassName = function () {
  50591. return "FreeCameraTouchInput";
  50592. };
  50593. FreeCameraTouchInput.prototype.getSimpleName = function () {
  50594. return "touch";
  50595. };
  50596. __decorate([
  50597. BABYLON.serialize()
  50598. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  50599. __decorate([
  50600. BABYLON.serialize()
  50601. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  50602. return FreeCameraTouchInput;
  50603. }());
  50604. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  50605. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  50606. })(BABYLON || (BABYLON = {}));
  50607. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  50608. /// <reference path="babylon.freeCamera.ts" />
  50609. var BABYLON;
  50610. (function (BABYLON) {
  50611. // We're mainly based on the logic defined into the FreeCamera code
  50612. var TouchCamera = (function (_super) {
  50613. __extends(TouchCamera, _super);
  50614. //-- end properties for backward compatibility for inputs
  50615. function TouchCamera(name, position, scene) {
  50616. var _this = _super.call(this, name, position, scene) || this;
  50617. _this.inputs.addTouch();
  50618. _this._setupInputs();
  50619. return _this;
  50620. }
  50621. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  50622. //-- Begin properties for backward compatibility for inputs
  50623. get: function () {
  50624. var touch = this.inputs.attached["touch"];
  50625. if (touch)
  50626. return touch.touchAngularSensibility;
  50627. },
  50628. set: function (value) {
  50629. var touch = this.inputs.attached["touch"];
  50630. if (touch)
  50631. touch.touchAngularSensibility = value;
  50632. },
  50633. enumerable: true,
  50634. configurable: true
  50635. });
  50636. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  50637. get: function () {
  50638. var touch = this.inputs.attached["touch"];
  50639. if (touch)
  50640. return touch.touchMoveSensibility;
  50641. },
  50642. set: function (value) {
  50643. var touch = this.inputs.attached["touch"];
  50644. if (touch)
  50645. touch.touchMoveSensibility = value;
  50646. },
  50647. enumerable: true,
  50648. configurable: true
  50649. });
  50650. TouchCamera.prototype.getClassName = function () {
  50651. return "TouchCamera";
  50652. };
  50653. TouchCamera.prototype._setupInputs = function () {
  50654. var mouse = this.inputs.attached["mouse"];
  50655. if (mouse) {
  50656. mouse.touchEnabled = false;
  50657. }
  50658. };
  50659. return TouchCamera;
  50660. }(BABYLON.FreeCamera));
  50661. BABYLON.TouchCamera = TouchCamera;
  50662. })(BABYLON || (BABYLON = {}));
  50663. //# sourceMappingURL=babylon.touchCamera.js.map
  50664. var BABYLON;
  50665. (function (BABYLON) {
  50666. var ProceduralTexture = (function (_super) {
  50667. __extends(ProceduralTexture, _super);
  50668. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  50669. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50670. if (isCube === void 0) { isCube = false; }
  50671. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50672. _this.isCube = isCube;
  50673. _this.isEnabled = true;
  50674. _this._currentRefreshId = -1;
  50675. _this._refreshRate = 1;
  50676. _this._vertexBuffers = {};
  50677. _this._uniforms = new Array();
  50678. _this._samplers = new Array();
  50679. _this._textures = new Array();
  50680. _this._floats = new Array();
  50681. _this._floatsArrays = {};
  50682. _this._colors3 = new Array();
  50683. _this._colors4 = new Array();
  50684. _this._vectors2 = new Array();
  50685. _this._vectors3 = new Array();
  50686. _this._matrices = new Array();
  50687. _this._fallbackTextureUsed = false;
  50688. scene._proceduralTextures.push(_this);
  50689. _this.name = name;
  50690. _this.isRenderTarget = true;
  50691. _this._size = size;
  50692. _this._generateMipMaps = generateMipMaps;
  50693. _this.setFragment(fragment);
  50694. _this._fallbackTexture = fallbackTexture;
  50695. var engine = scene.getEngine();
  50696. if (isCube) {
  50697. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  50698. _this.setFloat("face", 0);
  50699. }
  50700. else {
  50701. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  50702. }
  50703. // VBO
  50704. var vertices = [];
  50705. vertices.push(1, 1);
  50706. vertices.push(-1, 1);
  50707. vertices.push(-1, -1);
  50708. vertices.push(1, -1);
  50709. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50710. _this._createIndexBuffer();
  50711. return _this;
  50712. }
  50713. ProceduralTexture.prototype._createIndexBuffer = function () {
  50714. var engine = this.getScene().getEngine();
  50715. // Indices
  50716. var indices = [];
  50717. indices.push(0);
  50718. indices.push(1);
  50719. indices.push(2);
  50720. indices.push(0);
  50721. indices.push(2);
  50722. indices.push(3);
  50723. this._indexBuffer = engine.createIndexBuffer(indices);
  50724. };
  50725. ProceduralTexture.prototype._rebuild = function () {
  50726. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  50727. this._createIndexBuffer();
  50728. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50729. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50730. }
  50731. };
  50732. ProceduralTexture.prototype.reset = function () {
  50733. if (this._effect === undefined) {
  50734. return;
  50735. }
  50736. var engine = this.getScene().getEngine();
  50737. engine._releaseEffect(this._effect);
  50738. };
  50739. ProceduralTexture.prototype.isReady = function () {
  50740. var _this = this;
  50741. var engine = this.getScene().getEngine();
  50742. var shaders;
  50743. if (!this._fragment) {
  50744. return false;
  50745. }
  50746. if (this._fallbackTextureUsed) {
  50747. return true;
  50748. }
  50749. if (this._fragment.fragmentElement !== undefined) {
  50750. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  50751. }
  50752. else {
  50753. shaders = { vertex: "procedural", fragment: this._fragment };
  50754. }
  50755. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  50756. _this.releaseInternalTexture();
  50757. if (_this._fallbackTexture) {
  50758. _this._texture = _this._fallbackTexture._texture;
  50759. _this._texture.incrementReferences();
  50760. }
  50761. _this._fallbackTextureUsed = true;
  50762. });
  50763. return this._effect.isReady();
  50764. };
  50765. ProceduralTexture.prototype.resetRefreshCounter = function () {
  50766. this._currentRefreshId = -1;
  50767. };
  50768. ProceduralTexture.prototype.setFragment = function (fragment) {
  50769. this._fragment = fragment;
  50770. };
  50771. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  50772. get: function () {
  50773. return this._refreshRate;
  50774. },
  50775. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50776. set: function (value) {
  50777. this._refreshRate = value;
  50778. this.resetRefreshCounter();
  50779. },
  50780. enumerable: true,
  50781. configurable: true
  50782. });
  50783. ProceduralTexture.prototype._shouldRender = function () {
  50784. if (!this.isEnabled || !this.isReady() || !this._texture) {
  50785. return false;
  50786. }
  50787. if (this._fallbackTextureUsed) {
  50788. return false;
  50789. }
  50790. if (this._currentRefreshId === -1) {
  50791. this._currentRefreshId = 1;
  50792. return true;
  50793. }
  50794. if (this.refreshRate === this._currentRefreshId) {
  50795. this._currentRefreshId = 1;
  50796. return true;
  50797. }
  50798. this._currentRefreshId++;
  50799. return false;
  50800. };
  50801. ProceduralTexture.prototype.getRenderSize = function () {
  50802. return this._size;
  50803. };
  50804. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  50805. if (this._fallbackTextureUsed) {
  50806. return;
  50807. }
  50808. this.releaseInternalTexture();
  50809. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  50810. };
  50811. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  50812. if (this._uniforms.indexOf(uniformName) === -1) {
  50813. this._uniforms.push(uniformName);
  50814. }
  50815. };
  50816. ProceduralTexture.prototype.setTexture = function (name, texture) {
  50817. if (this._samplers.indexOf(name) === -1) {
  50818. this._samplers.push(name);
  50819. }
  50820. this._textures[name] = texture;
  50821. return this;
  50822. };
  50823. ProceduralTexture.prototype.setFloat = function (name, value) {
  50824. this._checkUniform(name);
  50825. this._floats[name] = value;
  50826. return this;
  50827. };
  50828. ProceduralTexture.prototype.setFloats = function (name, value) {
  50829. this._checkUniform(name);
  50830. this._floatsArrays[name] = value;
  50831. return this;
  50832. };
  50833. ProceduralTexture.prototype.setColor3 = function (name, value) {
  50834. this._checkUniform(name);
  50835. this._colors3[name] = value;
  50836. return this;
  50837. };
  50838. ProceduralTexture.prototype.setColor4 = function (name, value) {
  50839. this._checkUniform(name);
  50840. this._colors4[name] = value;
  50841. return this;
  50842. };
  50843. ProceduralTexture.prototype.setVector2 = function (name, value) {
  50844. this._checkUniform(name);
  50845. this._vectors2[name] = value;
  50846. return this;
  50847. };
  50848. ProceduralTexture.prototype.setVector3 = function (name, value) {
  50849. this._checkUniform(name);
  50850. this._vectors3[name] = value;
  50851. return this;
  50852. };
  50853. ProceduralTexture.prototype.setMatrix = function (name, value) {
  50854. this._checkUniform(name);
  50855. this._matrices[name] = value;
  50856. return this;
  50857. };
  50858. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50859. var scene = this.getScene();
  50860. var engine = scene.getEngine();
  50861. // Render
  50862. engine.enableEffect(this._effect);
  50863. engine.setState(false);
  50864. // Texture
  50865. for (var name in this._textures) {
  50866. this._effect.setTexture(name, this._textures[name]);
  50867. }
  50868. // Float
  50869. for (name in this._floats) {
  50870. this._effect.setFloat(name, this._floats[name]);
  50871. }
  50872. // Floats
  50873. for (name in this._floatsArrays) {
  50874. this._effect.setArray(name, this._floatsArrays[name]);
  50875. }
  50876. // Color3
  50877. for (name in this._colors3) {
  50878. this._effect.setColor3(name, this._colors3[name]);
  50879. }
  50880. // Color4
  50881. for (name in this._colors4) {
  50882. var color = this._colors4[name];
  50883. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50884. }
  50885. // Vector2
  50886. for (name in this._vectors2) {
  50887. this._effect.setVector2(name, this._vectors2[name]);
  50888. }
  50889. // Vector3
  50890. for (name in this._vectors3) {
  50891. this._effect.setVector3(name, this._vectors3[name]);
  50892. }
  50893. // Matrix
  50894. for (name in this._matrices) {
  50895. this._effect.setMatrix(name, this._matrices[name]);
  50896. }
  50897. if (this.isCube) {
  50898. for (var face = 0; face < 6; face++) {
  50899. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  50900. // VBOs
  50901. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50902. this._effect.setFloat("face", face);
  50903. // Clear
  50904. engine.clear(scene.clearColor, true, true, true);
  50905. // Draw order
  50906. engine.draw(true, 0, 6);
  50907. // Mipmaps
  50908. if (face === 5) {
  50909. engine.generateMipMapsForCubemap(this._texture);
  50910. }
  50911. }
  50912. }
  50913. else {
  50914. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  50915. // VBOs
  50916. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50917. // Clear
  50918. engine.clear(scene.clearColor, true, true, true);
  50919. // Draw order
  50920. engine.draw(true, 0, 6);
  50921. }
  50922. // Unbind
  50923. engine.unBindFramebuffer(this._texture, this.isCube);
  50924. if (this.onGenerated) {
  50925. this.onGenerated();
  50926. }
  50927. };
  50928. ProceduralTexture.prototype.clone = function () {
  50929. var textureSize = this.getSize();
  50930. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  50931. // Base texture
  50932. newTexture.hasAlpha = this.hasAlpha;
  50933. newTexture.level = this.level;
  50934. // RenderTarget Texture
  50935. newTexture.coordinatesMode = this.coordinatesMode;
  50936. return newTexture;
  50937. };
  50938. ProceduralTexture.prototype.dispose = function () {
  50939. var index = this.getScene()._proceduralTextures.indexOf(this);
  50940. if (index >= 0) {
  50941. this.getScene()._proceduralTextures.splice(index, 1);
  50942. }
  50943. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50944. if (vertexBuffer) {
  50945. vertexBuffer.dispose();
  50946. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50947. }
  50948. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  50949. this._indexBuffer = null;
  50950. }
  50951. _super.prototype.dispose.call(this);
  50952. };
  50953. return ProceduralTexture;
  50954. }(BABYLON.Texture));
  50955. BABYLON.ProceduralTexture = ProceduralTexture;
  50956. })(BABYLON || (BABYLON = {}));
  50957. //# sourceMappingURL=babylon.proceduralTexture.js.map
  50958. /// <reference path="babylon.proceduralTexture.ts" />
  50959. var BABYLON;
  50960. (function (BABYLON) {
  50961. var CustomProceduralTexture = (function (_super) {
  50962. __extends(CustomProceduralTexture, _super);
  50963. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  50964. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  50965. _this._animate = true;
  50966. _this._time = 0;
  50967. _this._texturePath = texturePath;
  50968. //Try to load json
  50969. _this.loadJson(texturePath);
  50970. _this.refreshRate = 1;
  50971. return _this;
  50972. }
  50973. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  50974. var _this = this;
  50975. var that = this;
  50976. function noConfigFile() {
  50977. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  50978. try {
  50979. that.setFragment(that._texturePath);
  50980. }
  50981. catch (ex) {
  50982. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  50983. }
  50984. }
  50985. var configFileUrl = jsonUrl + "/config.json";
  50986. var xhr = new XMLHttpRequest();
  50987. xhr.open("GET", configFileUrl, true);
  50988. xhr.addEventListener("load", function () {
  50989. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  50990. try {
  50991. _this._config = JSON.parse(xhr.response);
  50992. _this.updateShaderUniforms();
  50993. _this.updateTextures();
  50994. _this.setFragment(_this._texturePath + "/custom");
  50995. _this._animate = _this._config.animate;
  50996. _this.refreshRate = _this._config.refreshrate;
  50997. }
  50998. catch (ex) {
  50999. noConfigFile();
  51000. }
  51001. }
  51002. else {
  51003. noConfigFile();
  51004. }
  51005. }, false);
  51006. xhr.addEventListener("error", function () {
  51007. noConfigFile();
  51008. }, false);
  51009. try {
  51010. xhr.send();
  51011. }
  51012. catch (ex) {
  51013. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  51014. }
  51015. };
  51016. CustomProceduralTexture.prototype.isReady = function () {
  51017. if (!_super.prototype.isReady.call(this)) {
  51018. return false;
  51019. }
  51020. for (var name in this._textures) {
  51021. var texture = this._textures[name];
  51022. if (!texture.isReady()) {
  51023. return false;
  51024. }
  51025. }
  51026. return true;
  51027. };
  51028. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  51029. if (this._animate) {
  51030. this._time += this.getScene().getAnimationRatio() * 0.03;
  51031. this.updateShaderUniforms();
  51032. }
  51033. _super.prototype.render.call(this, useCameraPostProcess);
  51034. };
  51035. CustomProceduralTexture.prototype.updateTextures = function () {
  51036. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  51037. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  51038. }
  51039. };
  51040. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  51041. if (this._config) {
  51042. for (var j = 0; j < this._config.uniforms.length; j++) {
  51043. var uniform = this._config.uniforms[j];
  51044. switch (uniform.type) {
  51045. case "float":
  51046. this.setFloat(uniform.name, uniform.value);
  51047. break;
  51048. case "color3":
  51049. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  51050. break;
  51051. case "color4":
  51052. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  51053. break;
  51054. case "vector2":
  51055. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  51056. break;
  51057. case "vector3":
  51058. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  51059. break;
  51060. }
  51061. }
  51062. }
  51063. this.setFloat("time", this._time);
  51064. };
  51065. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  51066. get: function () {
  51067. return this._animate;
  51068. },
  51069. set: function (value) {
  51070. this._animate = value;
  51071. },
  51072. enumerable: true,
  51073. configurable: true
  51074. });
  51075. return CustomProceduralTexture;
  51076. }(BABYLON.ProceduralTexture));
  51077. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  51078. })(BABYLON || (BABYLON = {}));
  51079. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  51080. var BABYLON;
  51081. (function (BABYLON) {
  51082. var FreeCameraGamepadInput = (function () {
  51083. function FreeCameraGamepadInput() {
  51084. this.gamepadAngularSensibility = 200;
  51085. this.gamepadMoveSensibility = 40;
  51086. // private members
  51087. this._cameraTransform = BABYLON.Matrix.Identity();
  51088. this._deltaTransform = BABYLON.Vector3.Zero();
  51089. this._vector3 = BABYLON.Vector3.Zero();
  51090. this._vector2 = BABYLON.Vector2.Zero();
  51091. }
  51092. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  51093. var _this = this;
  51094. var manager = this.camera.getScene().gamepadManager;
  51095. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  51096. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  51097. // prioritize XBOX gamepads.
  51098. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  51099. _this.gamepad = gamepad;
  51100. }
  51101. }
  51102. });
  51103. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  51104. if (_this.gamepad === gamepad) {
  51105. _this.gamepad = null;
  51106. }
  51107. });
  51108. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  51109. };
  51110. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  51111. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  51112. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  51113. this.gamepad = null;
  51114. };
  51115. FreeCameraGamepadInput.prototype.checkInputs = function () {
  51116. if (this.gamepad && this.gamepad.leftStick) {
  51117. var camera = this.camera;
  51118. var LSValues = this.gamepad.leftStick;
  51119. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  51120. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  51121. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  51122. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  51123. var RSValues = this.gamepad.rightStick;
  51124. if (RSValues) {
  51125. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  51126. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  51127. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  51128. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  51129. }
  51130. else {
  51131. RSValues = { x: 0, y: 0 };
  51132. }
  51133. if (!camera.rotationQuaternion) {
  51134. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  51135. }
  51136. else {
  51137. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  51138. }
  51139. var speed = camera._computeLocalCameraSpeed() * 50.0;
  51140. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  51141. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  51142. camera.cameraDirection.addInPlace(this._deltaTransform);
  51143. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  51144. camera.cameraRotation.addInPlace(this._vector2);
  51145. }
  51146. };
  51147. FreeCameraGamepadInput.prototype.getClassName = function () {
  51148. return "FreeCameraGamepadInput";
  51149. };
  51150. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  51151. return "gamepad";
  51152. };
  51153. __decorate([
  51154. BABYLON.serialize()
  51155. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  51156. __decorate([
  51157. BABYLON.serialize()
  51158. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51159. return FreeCameraGamepadInput;
  51160. }());
  51161. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  51162. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  51163. })(BABYLON || (BABYLON = {}));
  51164. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  51165. var BABYLON;
  51166. (function (BABYLON) {
  51167. var ArcRotateCameraGamepadInput = (function () {
  51168. function ArcRotateCameraGamepadInput() {
  51169. this.gamepadRotationSensibility = 80;
  51170. this.gamepadMoveSensibility = 40;
  51171. }
  51172. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  51173. var _this = this;
  51174. var manager = this.camera.getScene().gamepadManager;
  51175. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  51176. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  51177. // prioritize XBOX gamepads.
  51178. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  51179. _this.gamepad = gamepad;
  51180. }
  51181. }
  51182. });
  51183. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  51184. if (_this.gamepad === gamepad) {
  51185. _this.gamepad = null;
  51186. }
  51187. });
  51188. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  51189. };
  51190. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  51191. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  51192. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  51193. this.gamepad = null;
  51194. };
  51195. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  51196. if (this.gamepad) {
  51197. var camera = this.camera;
  51198. var RSValues = this.gamepad.rightStick;
  51199. if (RSValues) {
  51200. if (RSValues.x != 0) {
  51201. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  51202. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  51203. camera.inertialAlphaOffset += normalizedRX;
  51204. }
  51205. }
  51206. if (RSValues.y != 0) {
  51207. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  51208. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  51209. camera.inertialBetaOffset += normalizedRY;
  51210. }
  51211. }
  51212. }
  51213. var LSValues = this.gamepad.leftStick;
  51214. if (LSValues && LSValues.y != 0) {
  51215. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  51216. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  51217. this.camera.inertialRadiusOffset -= normalizedLY;
  51218. }
  51219. }
  51220. }
  51221. };
  51222. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  51223. return "ArcRotateCameraGamepadInput";
  51224. };
  51225. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  51226. return "gamepad";
  51227. };
  51228. __decorate([
  51229. BABYLON.serialize()
  51230. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  51231. __decorate([
  51232. BABYLON.serialize()
  51233. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51234. return ArcRotateCameraGamepadInput;
  51235. }());
  51236. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  51237. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  51238. })(BABYLON || (BABYLON = {}));
  51239. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  51240. var BABYLON;
  51241. (function (BABYLON) {
  51242. var GamepadManager = (function () {
  51243. function GamepadManager() {
  51244. var _this = this;
  51245. this._babylonGamepads = [];
  51246. this._oneGamepadConnected = false;
  51247. this._isMonitoring = false;
  51248. this._gamepadEventSupported = 'GamepadEvent' in window;
  51249. this._gamepadSupport = (navigator.getGamepads ||
  51250. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  51251. this.onGamepadConnectedObservable = new BABYLON.Observable();
  51252. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  51253. this._onGamepadConnectedEvent = function (evt) {
  51254. var gamepad = evt.gamepad;
  51255. if (gamepad.index in _this._babylonGamepads) {
  51256. if (_this._babylonGamepads[gamepad.index].isConnected) {
  51257. return;
  51258. }
  51259. }
  51260. var newGamepad;
  51261. if (_this._babylonGamepads[gamepad.index]) {
  51262. newGamepad = _this._babylonGamepads[gamepad.index];
  51263. newGamepad.browserGamepad = gamepad;
  51264. newGamepad._isConnected = true;
  51265. }
  51266. else {
  51267. newGamepad = _this._addNewGamepad(gamepad);
  51268. }
  51269. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51270. _this._startMonitoringGamepads();
  51271. };
  51272. this._onGamepadDisconnectedEvent = function (evt) {
  51273. var gamepad = evt.gamepad;
  51274. // Remove the gamepad from the list of gamepads to monitor.
  51275. for (var i in _this._babylonGamepads) {
  51276. if (_this._babylonGamepads[i].index === gamepad.index) {
  51277. var disconnectedGamepad = _this._babylonGamepads[i];
  51278. disconnectedGamepad._isConnected = false;
  51279. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  51280. break;
  51281. }
  51282. }
  51283. };
  51284. if (this._gamepadSupport) {
  51285. //first add already-connected gamepads
  51286. this._updateGamepadObjects();
  51287. if (this._babylonGamepads.length) {
  51288. this._startMonitoringGamepads();
  51289. }
  51290. // Checking if the gamepad connected event is supported (like in Firefox)
  51291. if (this._gamepadEventSupported) {
  51292. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  51293. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  51294. }
  51295. else {
  51296. this._startMonitoringGamepads();
  51297. }
  51298. }
  51299. }
  51300. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  51301. get: function () {
  51302. return this._babylonGamepads;
  51303. },
  51304. enumerable: true,
  51305. configurable: true
  51306. });
  51307. GamepadManager.prototype.getGamepadByType = function (type) {
  51308. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  51309. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  51310. var gamepad = _a[_i];
  51311. if (gamepad && gamepad.type === type) {
  51312. return gamepad;
  51313. }
  51314. }
  51315. return null;
  51316. };
  51317. GamepadManager.prototype.dispose = function () {
  51318. if (this._gamepadEventSupported) {
  51319. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  51320. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  51321. this._onGamepadConnectedEvent = null;
  51322. this._onGamepadDisconnectedEvent = null;
  51323. }
  51324. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  51325. var gamepad = _a[_i];
  51326. gamepad.dispose();
  51327. }
  51328. this._oneGamepadConnected = false;
  51329. this._stopMonitoringGamepads();
  51330. this._babylonGamepads = [];
  51331. };
  51332. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  51333. if (!this._oneGamepadConnected) {
  51334. this._oneGamepadConnected = true;
  51335. }
  51336. var newGamepad;
  51337. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  51338. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  51339. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  51340. }
  51341. else if (gamepad.pose) {
  51342. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  51343. }
  51344. else {
  51345. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  51346. }
  51347. this._babylonGamepads[newGamepad.index] = newGamepad;
  51348. return newGamepad;
  51349. };
  51350. GamepadManager.prototype._startMonitoringGamepads = function () {
  51351. if (!this._isMonitoring) {
  51352. this._isMonitoring = true;
  51353. this._checkGamepadsStatus();
  51354. }
  51355. };
  51356. GamepadManager.prototype._stopMonitoringGamepads = function () {
  51357. this._isMonitoring = false;
  51358. };
  51359. GamepadManager.prototype._checkGamepadsStatus = function () {
  51360. var _this = this;
  51361. // Hack to be compatible Chrome
  51362. this._updateGamepadObjects();
  51363. for (var i in this._babylonGamepads) {
  51364. var gamepad = this._babylonGamepads[i];
  51365. if (!gamepad || !gamepad.isConnected) {
  51366. continue;
  51367. }
  51368. gamepad.update();
  51369. }
  51370. if (this._isMonitoring) {
  51371. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  51372. }
  51373. };
  51374. // This function is called only on Chrome, which does not properly support
  51375. // connection/disconnection events and forces you to recopy again the gamepad object
  51376. GamepadManager.prototype._updateGamepadObjects = function () {
  51377. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  51378. for (var i = 0; i < gamepads.length; i++) {
  51379. if (gamepads[i]) {
  51380. if (!this._babylonGamepads[gamepads[i].index]) {
  51381. var newGamepad = this._addNewGamepad(gamepads[i]);
  51382. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51383. }
  51384. else {
  51385. // Forced to copy again this object for Chrome for unknown reason
  51386. this._babylonGamepads[i].browserGamepad = gamepads[i];
  51387. if (!this._babylonGamepads[i].isConnected) {
  51388. this._babylonGamepads[i]._isConnected = true;
  51389. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  51390. }
  51391. }
  51392. }
  51393. }
  51394. };
  51395. return GamepadManager;
  51396. }());
  51397. BABYLON.GamepadManager = GamepadManager;
  51398. })(BABYLON || (BABYLON = {}));
  51399. //# sourceMappingURL=babylon.gamepadManager.js.map
  51400. var BABYLON;
  51401. (function (BABYLON) {
  51402. var StickValues = (function () {
  51403. function StickValues(x, y) {
  51404. this.x = x;
  51405. this.y = y;
  51406. }
  51407. return StickValues;
  51408. }());
  51409. BABYLON.StickValues = StickValues;
  51410. var Gamepad = (function () {
  51411. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  51412. if (leftStickX === void 0) { leftStickX = 0; }
  51413. if (leftStickY === void 0) { leftStickY = 1; }
  51414. if (rightStickX === void 0) { rightStickX = 2; }
  51415. if (rightStickY === void 0) { rightStickY = 3; }
  51416. this.id = id;
  51417. this.index = index;
  51418. this.browserGamepad = browserGamepad;
  51419. this._isConnected = true;
  51420. this.type = Gamepad.GAMEPAD;
  51421. this._leftStickAxisX = leftStickX;
  51422. this._leftStickAxisY = leftStickY;
  51423. this._rightStickAxisX = rightStickX;
  51424. this._rightStickAxisY = rightStickY;
  51425. if (this.browserGamepad.axes.length >= 2) {
  51426. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51427. }
  51428. if (this.browserGamepad.axes.length >= 4) {
  51429. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51430. }
  51431. }
  51432. Object.defineProperty(Gamepad.prototype, "isConnected", {
  51433. get: function () {
  51434. return this._isConnected;
  51435. },
  51436. enumerable: true,
  51437. configurable: true
  51438. });
  51439. Gamepad.prototype.onleftstickchanged = function (callback) {
  51440. this._onleftstickchanged = callback;
  51441. };
  51442. Gamepad.prototype.onrightstickchanged = function (callback) {
  51443. this._onrightstickchanged = callback;
  51444. };
  51445. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51446. get: function () {
  51447. return this._leftStick;
  51448. },
  51449. set: function (newValues) {
  51450. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51451. this._onleftstickchanged(newValues);
  51452. }
  51453. this._leftStick = newValues;
  51454. },
  51455. enumerable: true,
  51456. configurable: true
  51457. });
  51458. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51459. get: function () {
  51460. return this._rightStick;
  51461. },
  51462. set: function (newValues) {
  51463. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51464. this._onrightstickchanged(newValues);
  51465. }
  51466. this._rightStick = newValues;
  51467. },
  51468. enumerable: true,
  51469. configurable: true
  51470. });
  51471. Gamepad.prototype.update = function () {
  51472. if (this._leftStick) {
  51473. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51474. }
  51475. if (this._rightStick) {
  51476. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51477. }
  51478. };
  51479. Gamepad.prototype.dispose = function () {
  51480. };
  51481. Gamepad.GAMEPAD = 0;
  51482. Gamepad.GENERIC = 1;
  51483. Gamepad.XBOX = 2;
  51484. Gamepad.POSE_ENABLED = 3;
  51485. return Gamepad;
  51486. }());
  51487. BABYLON.Gamepad = Gamepad;
  51488. var GenericPad = (function (_super) {
  51489. __extends(GenericPad, _super);
  51490. function GenericPad(id, index, browserGamepad) {
  51491. var _this = _super.call(this, id, index, browserGamepad) || this;
  51492. _this.type = Gamepad.GENERIC;
  51493. _this._buttons = new Array(browserGamepad.buttons.length);
  51494. return _this;
  51495. }
  51496. GenericPad.prototype.onbuttondown = function (callback) {
  51497. this._onbuttondown = callback;
  51498. };
  51499. GenericPad.prototype.onbuttonup = function (callback) {
  51500. this._onbuttonup = callback;
  51501. };
  51502. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51503. if (newValue !== currentValue) {
  51504. if (this._onbuttondown && newValue === 1) {
  51505. this._onbuttondown(buttonIndex);
  51506. }
  51507. if (this._onbuttonup && newValue === 0) {
  51508. this._onbuttonup(buttonIndex);
  51509. }
  51510. }
  51511. return newValue;
  51512. };
  51513. GenericPad.prototype.update = function () {
  51514. _super.prototype.update.call(this);
  51515. for (var index = 0; index < this._buttons.length; index++) {
  51516. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  51517. }
  51518. };
  51519. return GenericPad;
  51520. }(Gamepad));
  51521. BABYLON.GenericPad = GenericPad;
  51522. })(BABYLON || (BABYLON = {}));
  51523. //# sourceMappingURL=babylon.gamepad.js.map
  51524. var BABYLON;
  51525. (function (BABYLON) {
  51526. var Xbox360Button;
  51527. (function (Xbox360Button) {
  51528. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51529. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51530. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51531. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51532. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51533. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51534. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51535. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51536. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51537. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51538. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51539. var Xbox360Dpad;
  51540. (function (Xbox360Dpad) {
  51541. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51542. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51543. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51544. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51545. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51546. var Xbox360Pad = (function (_super) {
  51547. __extends(Xbox360Pad, _super);
  51548. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51549. if (xboxOne === void 0) { xboxOne = false; }
  51550. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  51551. _this._leftTrigger = 0;
  51552. _this._rightTrigger = 0;
  51553. _this._buttonA = 0;
  51554. _this._buttonB = 0;
  51555. _this._buttonX = 0;
  51556. _this._buttonY = 0;
  51557. _this._buttonBack = 0;
  51558. _this._buttonStart = 0;
  51559. _this._buttonLB = 0;
  51560. _this._buttonRB = 0;
  51561. _this._buttonLeftStick = 0;
  51562. _this._buttonRightStick = 0;
  51563. _this._dPadUp = 0;
  51564. _this._dPadDown = 0;
  51565. _this._dPadLeft = 0;
  51566. _this._dPadRight = 0;
  51567. _this._isXboxOnePad = false;
  51568. _this.type = BABYLON.Gamepad.XBOX;
  51569. _this._isXboxOnePad = xboxOne;
  51570. return _this;
  51571. }
  51572. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51573. this._onlefttriggerchanged = callback;
  51574. };
  51575. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51576. this._onrighttriggerchanged = callback;
  51577. };
  51578. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51579. get: function () {
  51580. return this._leftTrigger;
  51581. },
  51582. set: function (newValue) {
  51583. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51584. this._onlefttriggerchanged(newValue);
  51585. }
  51586. this._leftTrigger = newValue;
  51587. },
  51588. enumerable: true,
  51589. configurable: true
  51590. });
  51591. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51592. get: function () {
  51593. return this._rightTrigger;
  51594. },
  51595. set: function (newValue) {
  51596. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51597. this._onrighttriggerchanged(newValue);
  51598. }
  51599. this._rightTrigger = newValue;
  51600. },
  51601. enumerable: true,
  51602. configurable: true
  51603. });
  51604. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51605. this._onbuttondown = callback;
  51606. };
  51607. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51608. this._onbuttonup = callback;
  51609. };
  51610. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51611. this._ondpaddown = callback;
  51612. };
  51613. Xbox360Pad.prototype.ondpadup = function (callback) {
  51614. this._ondpadup = callback;
  51615. };
  51616. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51617. if (newValue !== currentValue) {
  51618. if (this._onbuttondown && newValue === 1) {
  51619. this._onbuttondown(buttonType);
  51620. }
  51621. if (this._onbuttonup && newValue === 0) {
  51622. this._onbuttonup(buttonType);
  51623. }
  51624. }
  51625. return newValue;
  51626. };
  51627. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51628. if (newValue !== currentValue) {
  51629. if (this._ondpaddown && newValue === 1) {
  51630. this._ondpaddown(buttonType);
  51631. }
  51632. if (this._ondpadup && newValue === 0) {
  51633. this._ondpadup(buttonType);
  51634. }
  51635. }
  51636. return newValue;
  51637. };
  51638. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51639. get: function () {
  51640. return this._buttonA;
  51641. },
  51642. set: function (value) {
  51643. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51644. },
  51645. enumerable: true,
  51646. configurable: true
  51647. });
  51648. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51649. get: function () {
  51650. return this._buttonB;
  51651. },
  51652. set: function (value) {
  51653. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51654. },
  51655. enumerable: true,
  51656. configurable: true
  51657. });
  51658. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51659. get: function () {
  51660. return this._buttonX;
  51661. },
  51662. set: function (value) {
  51663. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51664. },
  51665. enumerable: true,
  51666. configurable: true
  51667. });
  51668. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51669. get: function () {
  51670. return this._buttonY;
  51671. },
  51672. set: function (value) {
  51673. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51674. },
  51675. enumerable: true,
  51676. configurable: true
  51677. });
  51678. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51679. get: function () {
  51680. return this._buttonStart;
  51681. },
  51682. set: function (value) {
  51683. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51684. },
  51685. enumerable: true,
  51686. configurable: true
  51687. });
  51688. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51689. get: function () {
  51690. return this._buttonBack;
  51691. },
  51692. set: function (value) {
  51693. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51694. },
  51695. enumerable: true,
  51696. configurable: true
  51697. });
  51698. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51699. get: function () {
  51700. return this._buttonLB;
  51701. },
  51702. set: function (value) {
  51703. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51704. },
  51705. enumerable: true,
  51706. configurable: true
  51707. });
  51708. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51709. get: function () {
  51710. return this._buttonRB;
  51711. },
  51712. set: function (value) {
  51713. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51714. },
  51715. enumerable: true,
  51716. configurable: true
  51717. });
  51718. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51719. get: function () {
  51720. return this._buttonLeftStick;
  51721. },
  51722. set: function (value) {
  51723. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51724. },
  51725. enumerable: true,
  51726. configurable: true
  51727. });
  51728. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51729. get: function () {
  51730. return this._buttonRightStick;
  51731. },
  51732. set: function (value) {
  51733. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51734. },
  51735. enumerable: true,
  51736. configurable: true
  51737. });
  51738. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51739. get: function () {
  51740. return this._dPadUp;
  51741. },
  51742. set: function (value) {
  51743. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51744. },
  51745. enumerable: true,
  51746. configurable: true
  51747. });
  51748. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51749. get: function () {
  51750. return this._dPadDown;
  51751. },
  51752. set: function (value) {
  51753. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51754. },
  51755. enumerable: true,
  51756. configurable: true
  51757. });
  51758. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51759. get: function () {
  51760. return this._dPadLeft;
  51761. },
  51762. set: function (value) {
  51763. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51764. },
  51765. enumerable: true,
  51766. configurable: true
  51767. });
  51768. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51769. get: function () {
  51770. return this._dPadRight;
  51771. },
  51772. set: function (value) {
  51773. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51774. },
  51775. enumerable: true,
  51776. configurable: true
  51777. });
  51778. Xbox360Pad.prototype.update = function () {
  51779. _super.prototype.update.call(this);
  51780. if (this._isXboxOnePad) {
  51781. this.buttonA = this.browserGamepad.buttons[0].value;
  51782. this.buttonB = this.browserGamepad.buttons[1].value;
  51783. this.buttonX = this.browserGamepad.buttons[2].value;
  51784. this.buttonY = this.browserGamepad.buttons[3].value;
  51785. this.buttonLB = this.browserGamepad.buttons[4].value;
  51786. this.buttonRB = this.browserGamepad.buttons[5].value;
  51787. this.leftTrigger = this.browserGamepad.axes[2];
  51788. this.rightTrigger = this.browserGamepad.axes[5];
  51789. this.buttonBack = this.browserGamepad.buttons[9].value;
  51790. this.buttonStart = this.browserGamepad.buttons[8].value;
  51791. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51792. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51793. this.dPadUp = this.browserGamepad.buttons[11].value;
  51794. this.dPadDown = this.browserGamepad.buttons[12].value;
  51795. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51796. this.dPadRight = this.browserGamepad.buttons[14].value;
  51797. }
  51798. else {
  51799. this.buttonA = this.browserGamepad.buttons[0].value;
  51800. this.buttonB = this.browserGamepad.buttons[1].value;
  51801. this.buttonX = this.browserGamepad.buttons[2].value;
  51802. this.buttonY = this.browserGamepad.buttons[3].value;
  51803. this.buttonLB = this.browserGamepad.buttons[4].value;
  51804. this.buttonRB = this.browserGamepad.buttons[5].value;
  51805. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51806. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51807. this.buttonBack = this.browserGamepad.buttons[8].value;
  51808. this.buttonStart = this.browserGamepad.buttons[9].value;
  51809. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51810. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51811. this.dPadUp = this.browserGamepad.buttons[12].value;
  51812. this.dPadDown = this.browserGamepad.buttons[13].value;
  51813. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51814. this.dPadRight = this.browserGamepad.buttons[15].value;
  51815. }
  51816. };
  51817. return Xbox360Pad;
  51818. }(BABYLON.Gamepad));
  51819. BABYLON.Xbox360Pad = Xbox360Pad;
  51820. })(BABYLON || (BABYLON = {}));
  51821. //# sourceMappingURL=babylon.xboxGamepad.js.map
  51822. var BABYLON;
  51823. (function (BABYLON) {
  51824. var PoseEnabledControllerType;
  51825. (function (PoseEnabledControllerType) {
  51826. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51827. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51828. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  51829. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  51830. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51831. var PoseEnabledControllerHelper = (function () {
  51832. function PoseEnabledControllerHelper() {
  51833. }
  51834. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51835. // Oculus Touch
  51836. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51837. return new BABYLON.OculusTouchController(vrGamepad);
  51838. }
  51839. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  51840. return new BABYLON.WindowsMotionController(vrGamepad);
  51841. }
  51842. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  51843. return new BABYLON.ViveController(vrGamepad);
  51844. }
  51845. else {
  51846. return new BABYLON.GenericController(vrGamepad);
  51847. }
  51848. };
  51849. return PoseEnabledControllerHelper;
  51850. }());
  51851. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51852. var PoseEnabledController = (function (_super) {
  51853. __extends(PoseEnabledController, _super);
  51854. function PoseEnabledController(browserGamepad) {
  51855. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  51856. _this.deviceScaleFactor = 1;
  51857. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51858. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51859. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51860. _this.position = BABYLON.Vector3.Zero();
  51861. _this.rotationQuaternion = new BABYLON.Quaternion();
  51862. _this.devicePosition = BABYLON.Vector3.Zero();
  51863. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51864. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51865. _this._calculatedRotation = new BABYLON.Quaternion();
  51866. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51867. return _this;
  51868. }
  51869. PoseEnabledController.prototype.update = function () {
  51870. _super.prototype.update.call(this);
  51871. var pose = this.browserGamepad.pose;
  51872. this.updateFromDevice(pose);
  51873. if (this._mesh) {
  51874. this._mesh.position.copyFrom(this._calculatedPosition);
  51875. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51876. }
  51877. };
  51878. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51879. if (poseData) {
  51880. this.rawPose = poseData;
  51881. if (poseData.position) {
  51882. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51883. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51884. this.devicePosition.z *= -1;
  51885. }
  51886. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51887. this._calculatedPosition.addInPlace(this.position);
  51888. }
  51889. if (poseData.orientation) {
  51890. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51891. if (this._mesh) {
  51892. if (this._mesh.getScene().useRightHandedSystem) {
  51893. this.deviceRotationQuaternion.z *= -1;
  51894. this.deviceRotationQuaternion.w *= -1;
  51895. }
  51896. else {
  51897. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51898. }
  51899. }
  51900. // if the camera is set, rotate to the camera's rotation
  51901. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51902. }
  51903. }
  51904. };
  51905. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51906. if (this._mesh) {
  51907. this._mesh.parent = undefined;
  51908. }
  51909. this._mesh = mesh;
  51910. if (this._poseControlledCamera) {
  51911. this._mesh.parent = this._poseControlledCamera;
  51912. }
  51913. if (!this._mesh.rotationQuaternion) {
  51914. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51915. }
  51916. };
  51917. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51918. this._poseControlledCamera = camera;
  51919. if (this._mesh) {
  51920. this._mesh.parent = this._poseControlledCamera;
  51921. }
  51922. };
  51923. PoseEnabledController.prototype.dispose = function () {
  51924. if (this._mesh) {
  51925. this._mesh.dispose();
  51926. }
  51927. this._mesh = undefined;
  51928. _super.prototype.dispose.call(this);
  51929. };
  51930. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  51931. get: function () {
  51932. return this._mesh;
  51933. },
  51934. enumerable: true,
  51935. configurable: true
  51936. });
  51937. PoseEnabledController.prototype.getForwardRay = function (length) {
  51938. if (length === void 0) { length = 100; }
  51939. if (!this.mesh) {
  51940. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  51941. }
  51942. var m = this.mesh.getWorldMatrix();
  51943. var origin = m.getTranslation();
  51944. var forward = new BABYLON.Vector3(0, 0, -1);
  51945. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  51946. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  51947. return new BABYLON.Ray(origin, direction, length);
  51948. };
  51949. return PoseEnabledController;
  51950. }(BABYLON.Gamepad));
  51951. BABYLON.PoseEnabledController = PoseEnabledController;
  51952. })(BABYLON || (BABYLON = {}));
  51953. //# sourceMappingURL=babylon.poseEnabledController.js.map
  51954. var BABYLON;
  51955. (function (BABYLON) {
  51956. var WebVRController = (function (_super) {
  51957. __extends(WebVRController, _super);
  51958. function WebVRController(vrGamepad) {
  51959. var _this = _super.call(this, vrGamepad) || this;
  51960. // Observables
  51961. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51962. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51963. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51964. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51965. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51966. _this.pad = { x: 0, y: 0 };
  51967. // avoid GC, store state in a tmp object
  51968. _this._changes = {
  51969. pressChanged: false,
  51970. touchChanged: false,
  51971. valueChanged: false,
  51972. changed: false
  51973. };
  51974. _this._buttons = new Array(vrGamepad.buttons.length);
  51975. _this.hand = vrGamepad.hand;
  51976. return _this;
  51977. }
  51978. WebVRController.prototype.onButtonStateChange = function (callback) {
  51979. this._onButtonStateChange = callback;
  51980. };
  51981. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  51982. get: function () {
  51983. return this._defaultModel;
  51984. },
  51985. enumerable: true,
  51986. configurable: true
  51987. });
  51988. WebVRController.prototype.update = function () {
  51989. _super.prototype.update.call(this);
  51990. for (var index = 0; index < this._buttons.length; index++) {
  51991. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  51992. }
  51993. ;
  51994. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51995. this.pad.x = this.leftStick.x;
  51996. this.pad.y = this.leftStick.y;
  51997. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51998. }
  51999. };
  52000. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  52001. if (!newState) {
  52002. newState = {
  52003. pressed: false,
  52004. touched: false,
  52005. value: 0
  52006. };
  52007. }
  52008. if (!currentState) {
  52009. this._buttons[buttonIndex] = {
  52010. pressed: newState.pressed,
  52011. touched: newState.touched,
  52012. value: newState.value
  52013. };
  52014. return;
  52015. }
  52016. this._checkChanges(newState, currentState);
  52017. if (this._changes.changed) {
  52018. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  52019. this.handleButtonChange(buttonIndex, newState, this._changes);
  52020. }
  52021. this._buttons[buttonIndex].pressed = newState.pressed;
  52022. this._buttons[buttonIndex].touched = newState.touched;
  52023. // oculus triggers are never 0, thou not touched.
  52024. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  52025. };
  52026. WebVRController.prototype._checkChanges = function (newState, currentState) {
  52027. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  52028. this._changes.touchChanged = newState.touched !== currentState.touched;
  52029. this._changes.valueChanged = newState.value !== currentState.value;
  52030. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  52031. return this._changes;
  52032. };
  52033. WebVRController.prototype.dispose = function () {
  52034. _super.prototype.dispose.call(this);
  52035. this.onTriggerStateChangedObservable.clear();
  52036. this.onMainButtonStateChangedObservable.clear();
  52037. this.onSecondaryButtonStateChangedObservable.clear();
  52038. this.onPadStateChangedObservable.clear();
  52039. this.onPadValuesChangedObservable.clear();
  52040. };
  52041. return WebVRController;
  52042. }(BABYLON.PoseEnabledController));
  52043. BABYLON.WebVRController = WebVRController;
  52044. })(BABYLON || (BABYLON = {}));
  52045. //# sourceMappingURL=babylon.webVRController.js.map
  52046. var BABYLON;
  52047. (function (BABYLON) {
  52048. var OculusTouchController = (function (_super) {
  52049. __extends(OculusTouchController, _super);
  52050. function OculusTouchController(vrGamepad) {
  52051. var _this = _super.call(this, vrGamepad) || this;
  52052. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  52053. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  52054. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  52055. return _this;
  52056. }
  52057. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52058. var _this = this;
  52059. var meshName;
  52060. // Hand
  52061. if (this.hand === 'left') {
  52062. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  52063. }
  52064. else {
  52065. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  52066. }
  52067. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  52068. /*
  52069. Parent Mesh name: oculus_touch_left
  52070. - body
  52071. - trigger
  52072. - thumbstick
  52073. - grip
  52074. - button_y
  52075. - button_x
  52076. - button_enter
  52077. */
  52078. _this._defaultModel = newMeshes[1];
  52079. if (meshLoaded) {
  52080. meshLoaded(_this._defaultModel);
  52081. }
  52082. _this.attachToMesh(_this._defaultModel);
  52083. });
  52084. };
  52085. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  52086. // helper getters for left and right hand.
  52087. get: function () {
  52088. if (this.hand === 'right') {
  52089. return this.onMainButtonStateChangedObservable;
  52090. }
  52091. else {
  52092. throw new Error('No A button on left hand');
  52093. }
  52094. },
  52095. enumerable: true,
  52096. configurable: true
  52097. });
  52098. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  52099. get: function () {
  52100. if (this.hand === 'right') {
  52101. return this.onSecondaryButtonStateChangedObservable;
  52102. }
  52103. else {
  52104. throw new Error('No B button on left hand');
  52105. }
  52106. },
  52107. enumerable: true,
  52108. configurable: true
  52109. });
  52110. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  52111. get: function () {
  52112. if (this.hand === 'left') {
  52113. return this.onMainButtonStateChangedObservable;
  52114. }
  52115. else {
  52116. throw new Error('No X button on right hand');
  52117. }
  52118. },
  52119. enumerable: true,
  52120. configurable: true
  52121. });
  52122. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  52123. get: function () {
  52124. if (this.hand === 'left') {
  52125. return this.onSecondaryButtonStateChangedObservable;
  52126. }
  52127. else {
  52128. throw new Error('No Y button on right hand');
  52129. }
  52130. },
  52131. enumerable: true,
  52132. configurable: true
  52133. });
  52134. /*
  52135. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  52136. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  52137. 2) secondary trigger (same)
  52138. 3) A (right) X (left), touch, pressed = value
  52139. 4) B / Y
  52140. 5) thumb rest
  52141. */
  52142. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52143. var notifyObject = state; //{ state: state, changes: changes };
  52144. var triggerDirection = this.hand === 'right' ? -1 : 1;
  52145. switch (buttonIdx) {
  52146. case 0:
  52147. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52148. return;
  52149. case 1:// index trigger
  52150. if (this._defaultModel) {
  52151. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  52152. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  52153. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  52154. }
  52155. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52156. return;
  52157. case 2:// secondary trigger
  52158. if (this._defaultModel) {
  52159. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  52160. }
  52161. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  52162. return;
  52163. case 3:
  52164. if (this._defaultModel) {
  52165. if (notifyObject.pressed) {
  52166. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  52167. }
  52168. else {
  52169. (this._defaultModel.getChildren()[1]).position.y = 0;
  52170. }
  52171. }
  52172. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52173. return;
  52174. case 4:
  52175. if (this._defaultModel) {
  52176. if (notifyObject.pressed) {
  52177. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52178. }
  52179. else {
  52180. (this._defaultModel.getChildren()[2]).position.y = 0;
  52181. }
  52182. }
  52183. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52184. return;
  52185. case 5:
  52186. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  52187. return;
  52188. }
  52189. };
  52190. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  52191. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  52192. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  52193. return OculusTouchController;
  52194. }(BABYLON.WebVRController));
  52195. BABYLON.OculusTouchController = OculusTouchController;
  52196. })(BABYLON || (BABYLON = {}));
  52197. //# sourceMappingURL=babylon.oculusTouchController.js.map
  52198. var BABYLON;
  52199. (function (BABYLON) {
  52200. var ViveController = (function (_super) {
  52201. __extends(ViveController, _super);
  52202. function ViveController(vrGamepad) {
  52203. var _this = _super.call(this, vrGamepad) || this;
  52204. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  52205. return _this;
  52206. }
  52207. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52208. var _this = this;
  52209. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  52210. /*
  52211. Parent Mesh name: ViveWand
  52212. - body
  52213. - r_gripper
  52214. - l_gripper
  52215. - menu_button
  52216. - system_button
  52217. - trackpad
  52218. - trigger
  52219. - LED
  52220. */
  52221. _this._defaultModel = newMeshes[1];
  52222. if (meshLoaded) {
  52223. meshLoaded(_this._defaultModel);
  52224. }
  52225. _this.attachToMesh(_this._defaultModel);
  52226. });
  52227. };
  52228. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  52229. get: function () {
  52230. return this.onMainButtonStateChangedObservable;
  52231. },
  52232. enumerable: true,
  52233. configurable: true
  52234. });
  52235. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  52236. get: function () {
  52237. return this.onMainButtonStateChangedObservable;
  52238. },
  52239. enumerable: true,
  52240. configurable: true
  52241. });
  52242. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  52243. get: function () {
  52244. return this.onSecondaryButtonStateChangedObservable;
  52245. },
  52246. enumerable: true,
  52247. configurable: true
  52248. });
  52249. /**
  52250. * Vive mapping:
  52251. * 0: touchpad
  52252. * 1: trigger
  52253. * 2: left AND right buttons
  52254. * 3: menu button
  52255. */
  52256. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52257. var notifyObject = state; //{ state: state, changes: changes };
  52258. switch (buttonIdx) {
  52259. case 0:
  52260. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52261. return;
  52262. case 1:// index trigger
  52263. if (this._defaultModel) {
  52264. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  52265. }
  52266. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52267. return;
  52268. case 2:// left AND right button
  52269. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52270. return;
  52271. case 3:
  52272. if (this._defaultModel) {
  52273. if (notifyObject.pressed) {
  52274. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52275. }
  52276. else {
  52277. (this._defaultModel.getChildren()[2]).position.y = 0;
  52278. }
  52279. }
  52280. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52281. return;
  52282. }
  52283. };
  52284. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  52285. ViveController.MODEL_FILENAME = 'wand.babylon';
  52286. return ViveController;
  52287. }(BABYLON.WebVRController));
  52288. BABYLON.ViveController = ViveController;
  52289. })(BABYLON || (BABYLON = {}));
  52290. //# sourceMappingURL=babylon.viveController.js.map
  52291. var BABYLON;
  52292. (function (BABYLON) {
  52293. var GenericController = (function (_super) {
  52294. __extends(GenericController, _super);
  52295. function GenericController(vrGamepad) {
  52296. return _super.call(this, vrGamepad) || this;
  52297. }
  52298. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52299. var _this = this;
  52300. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  52301. _this._defaultModel = newMeshes[1];
  52302. if (meshLoaded) {
  52303. meshLoaded(_this._defaultModel);
  52304. }
  52305. _this.attachToMesh(_this._defaultModel);
  52306. });
  52307. };
  52308. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52309. console.log("Button id: " + buttonIdx + "state: ");
  52310. console.dir(state);
  52311. };
  52312. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  52313. GenericController.MODEL_FILENAME = 'generic.babylon';
  52314. return GenericController;
  52315. }(BABYLON.WebVRController));
  52316. BABYLON.GenericController = GenericController;
  52317. })(BABYLON || (BABYLON = {}));
  52318. //# sourceMappingURL=babylon.genericController.js.map
  52319. var BABYLON;
  52320. (function (BABYLON) {
  52321. var LoadedMeshInfo = (function () {
  52322. function LoadedMeshInfo() {
  52323. this.buttonMeshes = {};
  52324. this.axisMeshes = {};
  52325. }
  52326. return LoadedMeshInfo;
  52327. }());
  52328. var WindowsMotionController = (function (_super) {
  52329. __extends(WindowsMotionController, _super);
  52330. function WindowsMotionController(vrGamepad) {
  52331. var _this = _super.call(this, vrGamepad) || this;
  52332. _this._mapping = {
  52333. // Semantic button names
  52334. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  52335. // A mapping of the button name to glTF model node name
  52336. // that should be transformed by button value.
  52337. buttonMeshNames: {
  52338. 'trigger': 'SELECT',
  52339. 'menu': 'MENU',
  52340. 'grip': 'GRASP',
  52341. 'thumbstick': 'THUMBSTICK_PRESS',
  52342. 'trackpad': 'TOUCHPAD_PRESS'
  52343. },
  52344. // This mapping is used to translate from the Motion Controller to Babylon semantics
  52345. buttonObservableNames: {
  52346. 'trigger': 'onTriggerStateChangedObservable',
  52347. 'menu': 'onSecondaryButtonStateChangedObservable',
  52348. 'grip': 'onMainButtonStateChangedObservable',
  52349. 'thumbstick': 'onPadStateChangedObservable',
  52350. 'trackpad': 'onTrackpadChangedObservable'
  52351. },
  52352. // A mapping of the axis name to glTF model node name
  52353. // that should be transformed by axis value.
  52354. // This array mirrors the browserGamepad.axes array, such that
  52355. // the mesh corresponding to axis 0 is in this array index 0.
  52356. axisMeshNames: [
  52357. 'THUMBSTICK_X',
  52358. 'THUMBSTICK_Y',
  52359. 'TOUCHPAD_TOUCH_X',
  52360. 'TOUCHPAD_TOUCH_Y'
  52361. ],
  52362. pointingPoseMeshName: 'POINTING_POSE'
  52363. };
  52364. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  52365. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  52366. _this._loadedMeshInfo = null;
  52367. return _this;
  52368. }
  52369. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  52370. get: function () {
  52371. return this.onTriggerStateChangedObservable;
  52372. },
  52373. enumerable: true,
  52374. configurable: true
  52375. });
  52376. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  52377. get: function () {
  52378. return this.onSecondaryButtonStateChangedObservable;
  52379. },
  52380. enumerable: true,
  52381. configurable: true
  52382. });
  52383. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  52384. get: function () {
  52385. return this.onMainButtonStateChangedObservable;
  52386. },
  52387. enumerable: true,
  52388. configurable: true
  52389. });
  52390. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  52391. get: function () {
  52392. return this.onPadStateChangedObservable;
  52393. },
  52394. enumerable: true,
  52395. configurable: true
  52396. });
  52397. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  52398. get: function () {
  52399. return this.onTrackpadChangedObservable;
  52400. },
  52401. enumerable: true,
  52402. configurable: true
  52403. });
  52404. /**
  52405. * Called once per frame by the engine.
  52406. */
  52407. WindowsMotionController.prototype.update = function () {
  52408. _super.prototype.update.call(this);
  52409. // Only need to animate axes if there is a loaded mesh
  52410. if (this._loadedMeshInfo) {
  52411. if (this.browserGamepad.axes) {
  52412. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  52413. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  52414. }
  52415. }
  52416. }
  52417. };
  52418. /**
  52419. * Called once for each button that changed state since the last frame
  52420. * @param buttonIdx Which button index changed
  52421. * @param state New state of the button
  52422. * @param changes Which properties on the state changed since last frame
  52423. */
  52424. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52425. var buttonName = this._mapping.buttons[buttonIdx];
  52426. if (!buttonName) {
  52427. return;
  52428. }
  52429. // Only emit events for buttons that we know how to map from index to name
  52430. var observable = this[this._mapping.buttonObservableNames[buttonName]];
  52431. if (observable) {
  52432. observable.notifyObservers(state);
  52433. }
  52434. this.lerpButtonTransform(buttonName, state.value);
  52435. };
  52436. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  52437. // If there is no loaded mesh, there is nothing to transform.
  52438. if (!this._loadedMeshInfo) {
  52439. return;
  52440. }
  52441. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  52442. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  52443. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  52444. };
  52445. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  52446. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  52447. if (!meshInfo) {
  52448. return;
  52449. }
  52450. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  52451. var lerpValue = axisValue * 0.5 + 0.5;
  52452. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  52453. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  52454. };
  52455. /**
  52456. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  52457. * @param scene scene in which to add meshes
  52458. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  52459. */
  52460. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  52461. var _this = this;
  52462. if (forceDefault === void 0) { forceDefault = false; }
  52463. var path;
  52464. var filename;
  52465. // Checking if GLB loader is present
  52466. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  52467. // Determine the device specific folder based on the ID suffix
  52468. var device = 'default';
  52469. if (this.id && !forceDefault) {
  52470. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  52471. device = ((match && match[0]) || device);
  52472. }
  52473. // Hand
  52474. if (this.hand === 'left') {
  52475. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  52476. }
  52477. else {
  52478. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  52479. }
  52480. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  52481. }
  52482. else {
  52483. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  52484. path = BABYLON.GenericController.MODEL_BASE_URL;
  52485. filename = BABYLON.GenericController.MODEL_FILENAME;
  52486. }
  52487. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  52488. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  52489. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  52490. if (!_this._loadedMeshInfo) {
  52491. return;
  52492. }
  52493. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  52494. _this.attachToMesh(_this._defaultModel);
  52495. if (meshLoaded) {
  52496. meshLoaded(_this._defaultModel);
  52497. }
  52498. }, null, function (scene, message) {
  52499. BABYLON.Tools.Log(message);
  52500. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  52501. if (!forceDefault) {
  52502. _this.initControllerMesh(scene, meshLoaded, true);
  52503. }
  52504. });
  52505. };
  52506. /**
  52507. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  52508. * can be transformed by button presses and axes values, based on this._mapping.
  52509. *
  52510. * @param scene scene in which the meshes exist
  52511. * @param meshes list of meshes that make up the controller model to process
  52512. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  52513. */
  52514. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  52515. var loadedMeshInfo = null;
  52516. // Create a new mesh to contain the glTF hierarchy
  52517. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  52518. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  52519. var childMesh = null;
  52520. for (var i = 0; i < meshes.length; i++) {
  52521. var mesh = meshes[i];
  52522. if (!mesh.parent) {
  52523. // Exclude controller meshes from picking results
  52524. mesh.isPickable = false;
  52525. // Handle root node, attach to the new parentMesh
  52526. childMesh = mesh;
  52527. break;
  52528. }
  52529. }
  52530. if (childMesh) {
  52531. childMesh.setParent(parentMesh);
  52532. // Create our mesh info. Note that this method will always return non-null.
  52533. loadedMeshInfo = this.createMeshInfo(parentMesh);
  52534. }
  52535. else {
  52536. BABYLON.Tools.Warn('Could not find root node in model file.');
  52537. }
  52538. return loadedMeshInfo;
  52539. };
  52540. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  52541. var loadedMeshInfo = new LoadedMeshInfo();
  52542. var i;
  52543. loadedMeshInfo.rootNode = rootNode;
  52544. // Reset the caches
  52545. loadedMeshInfo.buttonMeshes = {};
  52546. loadedMeshInfo.axisMeshes = {};
  52547. // Button Meshes
  52548. for (i = 0; i < this._mapping.buttons.length; i++) {
  52549. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  52550. if (!buttonMeshName) {
  52551. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  52552. continue;
  52553. }
  52554. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  52555. if (!buttonMesh) {
  52556. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  52557. continue;
  52558. }
  52559. var buttonMeshInfo = {
  52560. index: i,
  52561. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  52562. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  52563. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  52564. };
  52565. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  52566. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  52567. }
  52568. else {
  52569. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  52570. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  52571. '(VALUE: ' + !!buttonMeshInfo.value +
  52572. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  52573. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  52574. ')');
  52575. }
  52576. }
  52577. // Axis Meshes
  52578. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  52579. var axisMeshName = this._mapping.axisMeshNames[i];
  52580. if (!axisMeshName) {
  52581. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  52582. continue;
  52583. }
  52584. var axisMesh = getChildByName(rootNode, axisMeshName);
  52585. if (!axisMesh) {
  52586. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  52587. continue;
  52588. }
  52589. var axisMeshInfo = {
  52590. index: i,
  52591. value: getImmediateChildByName(axisMesh, 'VALUE'),
  52592. min: getImmediateChildByName(axisMesh, 'MIN'),
  52593. max: getImmediateChildByName(axisMesh, 'MAX')
  52594. };
  52595. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  52596. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  52597. }
  52598. else {
  52599. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  52600. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  52601. '(VALUE: ' + !!axisMeshInfo.value +
  52602. ', MIN: ' + !!axisMeshInfo.min +
  52603. ', MAX:' + !!axisMeshInfo.max +
  52604. ')');
  52605. }
  52606. }
  52607. // Pointing Ray
  52608. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  52609. if (!loadedMeshInfo.pointingPoseNode) {
  52610. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  52611. }
  52612. return loadedMeshInfo;
  52613. // Look through all children recursively. This will return null if no mesh exists with the given name.
  52614. function getChildByName(node, name) {
  52615. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  52616. }
  52617. // Look through only immediate children. This will return null if no mesh exists with the given name.
  52618. function getImmediateChildByName(node, name) {
  52619. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  52620. }
  52621. };
  52622. WindowsMotionController.prototype.getForwardRay = function (length) {
  52623. if (length === void 0) { length = 100; }
  52624. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  52625. return _super.prototype.getForwardRay.call(this, length);
  52626. }
  52627. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  52628. var origin = m.getTranslation();
  52629. var forward = new BABYLON.Vector3(0, 0, -1);
  52630. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  52631. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  52632. return new BABYLON.Ray(origin, direction, length);
  52633. };
  52634. WindowsMotionController.prototype.dispose = function () {
  52635. _super.prototype.dispose.call(this);
  52636. this.onTrackpadChangedObservable.clear();
  52637. };
  52638. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  52639. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  52640. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  52641. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  52642. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  52643. return WindowsMotionController;
  52644. }(BABYLON.WebVRController));
  52645. BABYLON.WindowsMotionController = WindowsMotionController;
  52646. })(BABYLON || (BABYLON = {}));
  52647. //# sourceMappingURL=babylon.windowsMotionController.js.map
  52648. /// <reference path="babylon.targetCamera.ts" />
  52649. var BABYLON;
  52650. (function (BABYLON) {
  52651. var FollowCamera = (function (_super) {
  52652. __extends(FollowCamera, _super);
  52653. function FollowCamera(name, position, scene, lockedTarget) {
  52654. var _this = _super.call(this, name, position, scene) || this;
  52655. _this.radius = 12;
  52656. _this.rotationOffset = 0;
  52657. _this.heightOffset = 4;
  52658. _this.cameraAcceleration = 0.05;
  52659. _this.maxCameraSpeed = 20;
  52660. _this.lockedTarget = lockedTarget;
  52661. return _this;
  52662. }
  52663. FollowCamera.prototype.getRadians = function (degrees) {
  52664. return degrees * Math.PI / 180;
  52665. };
  52666. FollowCamera.prototype.follow = function (cameraTarget) {
  52667. if (!cameraTarget)
  52668. return;
  52669. var yRotation;
  52670. if (cameraTarget.rotationQuaternion) {
  52671. var rotMatrix = new BABYLON.Matrix();
  52672. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  52673. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  52674. }
  52675. else {
  52676. yRotation = cameraTarget.rotation.y;
  52677. }
  52678. var radians = this.getRadians(this.rotationOffset) + yRotation;
  52679. var targetPosition = cameraTarget.getAbsolutePosition();
  52680. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  52681. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  52682. var dx = targetX - this.position.x;
  52683. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  52684. var dz = (targetZ) - this.position.z;
  52685. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  52686. var vy = dy * this.cameraAcceleration;
  52687. var vz = dz * this.cameraAcceleration * 2;
  52688. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  52689. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52690. }
  52691. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  52692. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52693. }
  52694. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  52695. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52696. }
  52697. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  52698. this.setTarget(targetPosition);
  52699. };
  52700. FollowCamera.prototype._checkInputs = function () {
  52701. _super.prototype._checkInputs.call(this);
  52702. this.follow(this.lockedTarget);
  52703. };
  52704. FollowCamera.prototype.getClassName = function () {
  52705. return "FollowCamera";
  52706. };
  52707. __decorate([
  52708. BABYLON.serialize()
  52709. ], FollowCamera.prototype, "radius", void 0);
  52710. __decorate([
  52711. BABYLON.serialize()
  52712. ], FollowCamera.prototype, "rotationOffset", void 0);
  52713. __decorate([
  52714. BABYLON.serialize()
  52715. ], FollowCamera.prototype, "heightOffset", void 0);
  52716. __decorate([
  52717. BABYLON.serialize()
  52718. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  52719. __decorate([
  52720. BABYLON.serialize()
  52721. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  52722. __decorate([
  52723. BABYLON.serializeAsMeshReference("lockedTargetId")
  52724. ], FollowCamera.prototype, "lockedTarget", void 0);
  52725. return FollowCamera;
  52726. }(BABYLON.TargetCamera));
  52727. BABYLON.FollowCamera = FollowCamera;
  52728. var ArcFollowCamera = (function (_super) {
  52729. __extends(ArcFollowCamera, _super);
  52730. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  52731. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  52732. _this.alpha = alpha;
  52733. _this.beta = beta;
  52734. _this.radius = radius;
  52735. _this.target = target;
  52736. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  52737. _this.follow();
  52738. return _this;
  52739. }
  52740. ArcFollowCamera.prototype.follow = function () {
  52741. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  52742. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  52743. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  52744. var targetPosition = this.target.getAbsolutePosition();
  52745. this.position = targetPosition.add(this._cartesianCoordinates);
  52746. this.setTarget(targetPosition);
  52747. };
  52748. ArcFollowCamera.prototype._checkInputs = function () {
  52749. _super.prototype._checkInputs.call(this);
  52750. this.follow();
  52751. };
  52752. ArcFollowCamera.prototype.getClassName = function () {
  52753. return "ArcFollowCamera";
  52754. };
  52755. return ArcFollowCamera;
  52756. }(BABYLON.TargetCamera));
  52757. BABYLON.ArcFollowCamera = ArcFollowCamera;
  52758. })(BABYLON || (BABYLON = {}));
  52759. //# sourceMappingURL=babylon.followCamera.js.map
  52760. /// <reference path="babylon.touchCamera.ts" />
  52761. var BABYLON;
  52762. (function (BABYLON) {
  52763. // We're mainly based on the logic defined into the FreeCamera code
  52764. var UniversalCamera = (function (_super) {
  52765. __extends(UniversalCamera, _super);
  52766. //-- end properties for backward compatibility for inputs
  52767. function UniversalCamera(name, position, scene) {
  52768. var _this = _super.call(this, name, position, scene) || this;
  52769. _this.inputs.addGamepad();
  52770. return _this;
  52771. }
  52772. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52773. //-- Begin properties for backward compatibility for inputs
  52774. get: function () {
  52775. var gamepad = this.inputs.attached["gamepad"];
  52776. if (gamepad)
  52777. return gamepad.gamepadAngularSensibility;
  52778. },
  52779. set: function (value) {
  52780. var gamepad = this.inputs.attached["gamepad"];
  52781. if (gamepad)
  52782. gamepad.gamepadAngularSensibility = value;
  52783. },
  52784. enumerable: true,
  52785. configurable: true
  52786. });
  52787. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52788. get: function () {
  52789. var gamepad = this.inputs.attached["gamepad"];
  52790. if (gamepad)
  52791. return gamepad.gamepadMoveSensibility;
  52792. },
  52793. set: function (value) {
  52794. var gamepad = this.inputs.attached["gamepad"];
  52795. if (gamepad)
  52796. gamepad.gamepadMoveSensibility = value;
  52797. },
  52798. enumerable: true,
  52799. configurable: true
  52800. });
  52801. UniversalCamera.prototype.getClassName = function () {
  52802. return "UniversalCamera";
  52803. };
  52804. return UniversalCamera;
  52805. }(BABYLON.TouchCamera));
  52806. BABYLON.UniversalCamera = UniversalCamera;
  52807. })(BABYLON || (BABYLON = {}));
  52808. //# sourceMappingURL=babylon.universalCamera.js.map
  52809. /// <reference path="babylon.universalCamera.ts" />
  52810. var BABYLON;
  52811. (function (BABYLON) {
  52812. // We're mainly based on the logic defined into the FreeCamera code
  52813. var GamepadCamera = (function (_super) {
  52814. __extends(GamepadCamera, _super);
  52815. //-- end properties for backward compatibility for inputs
  52816. function GamepadCamera(name, position, scene) {
  52817. return _super.call(this, name, position, scene) || this;
  52818. }
  52819. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  52820. //-- Begin properties for backward compatibility for inputs
  52821. get: function () {
  52822. var gamepad = this.inputs.attached["gamepad"];
  52823. if (gamepad)
  52824. return gamepad.gamepadAngularSensibility;
  52825. },
  52826. set: function (value) {
  52827. var gamepad = this.inputs.attached["gamepad"];
  52828. if (gamepad)
  52829. gamepad.gamepadAngularSensibility = value;
  52830. },
  52831. enumerable: true,
  52832. configurable: true
  52833. });
  52834. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  52835. get: function () {
  52836. var gamepad = this.inputs.attached["gamepad"];
  52837. if (gamepad)
  52838. return gamepad.gamepadMoveSensibility;
  52839. },
  52840. set: function (value) {
  52841. var gamepad = this.inputs.attached["gamepad"];
  52842. if (gamepad)
  52843. gamepad.gamepadMoveSensibility = value;
  52844. },
  52845. enumerable: true,
  52846. configurable: true
  52847. });
  52848. GamepadCamera.prototype.getClassName = function () {
  52849. return "GamepadCamera";
  52850. };
  52851. return GamepadCamera;
  52852. }(BABYLON.UniversalCamera));
  52853. BABYLON.GamepadCamera = GamepadCamera;
  52854. })(BABYLON || (BABYLON = {}));
  52855. //# sourceMappingURL=babylon.gamepadCamera.js.map
  52856. var BABYLON;
  52857. (function (BABYLON) {
  52858. var PostProcessRenderPipelineManager = (function () {
  52859. function PostProcessRenderPipelineManager() {
  52860. this._renderPipelines = {};
  52861. }
  52862. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  52863. this._renderPipelines[renderPipeline._name] = renderPipeline;
  52864. };
  52865. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  52866. var renderPipeline = this._renderPipelines[renderPipelineName];
  52867. if (!renderPipeline) {
  52868. return;
  52869. }
  52870. renderPipeline._attachCameras(cameras, unique);
  52871. };
  52872. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  52873. var renderPipeline = this._renderPipelines[renderPipelineName];
  52874. if (!renderPipeline) {
  52875. return;
  52876. }
  52877. renderPipeline._detachCameras(cameras);
  52878. };
  52879. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  52880. var renderPipeline = this._renderPipelines[renderPipelineName];
  52881. if (!renderPipeline) {
  52882. return;
  52883. }
  52884. renderPipeline._enableEffect(renderEffectName, cameras);
  52885. };
  52886. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  52887. var renderPipeline = this._renderPipelines[renderPipelineName];
  52888. if (!renderPipeline) {
  52889. return;
  52890. }
  52891. renderPipeline._disableEffect(renderEffectName, cameras);
  52892. };
  52893. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  52894. var renderPipeline = this._renderPipelines[renderPipelineName];
  52895. if (!renderPipeline) {
  52896. return;
  52897. }
  52898. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  52899. };
  52900. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  52901. var renderPipeline = this._renderPipelines[renderPipelineName];
  52902. if (!renderPipeline) {
  52903. return;
  52904. }
  52905. renderPipeline._disableDisplayOnlyPass(cameras);
  52906. };
  52907. PostProcessRenderPipelineManager.prototype.update = function () {
  52908. for (var renderPipelineName in this._renderPipelines) {
  52909. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52910. var pipeline = this._renderPipelines[renderPipelineName];
  52911. if (!pipeline.isSupported) {
  52912. pipeline.dispose();
  52913. delete this._renderPipelines[renderPipelineName];
  52914. }
  52915. else {
  52916. pipeline._update();
  52917. }
  52918. }
  52919. }
  52920. };
  52921. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  52922. for (var renderPipelineName in this._renderPipelines) {
  52923. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52924. var pipeline = this._renderPipelines[renderPipelineName];
  52925. pipeline._rebuild();
  52926. }
  52927. }
  52928. };
  52929. PostProcessRenderPipelineManager.prototype.dispose = function () {
  52930. for (var renderPipelineName in this._renderPipelines) {
  52931. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52932. var pipeline = this._renderPipelines[renderPipelineName];
  52933. pipeline.dispose();
  52934. }
  52935. }
  52936. };
  52937. return PostProcessRenderPipelineManager;
  52938. }());
  52939. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  52940. })(BABYLON || (BABYLON = {}));
  52941. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  52942. var BABYLON;
  52943. (function (BABYLON) {
  52944. var PostProcessRenderPass = (function () {
  52945. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  52946. this._enabled = true;
  52947. this._refCount = 0;
  52948. this._name = name;
  52949. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  52950. this.setRenderList(renderList);
  52951. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  52952. this._renderTexture.onAfterRenderObservable.add(afterRender);
  52953. this._scene = scene;
  52954. this._renderList = renderList;
  52955. }
  52956. // private
  52957. PostProcessRenderPass.prototype._incRefCount = function () {
  52958. if (this._refCount === 0) {
  52959. this._scene.customRenderTargets.push(this._renderTexture);
  52960. }
  52961. return ++this._refCount;
  52962. };
  52963. PostProcessRenderPass.prototype._decRefCount = function () {
  52964. this._refCount--;
  52965. if (this._refCount <= 0) {
  52966. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  52967. }
  52968. return this._refCount;
  52969. };
  52970. PostProcessRenderPass.prototype._update = function () {
  52971. this.setRenderList(this._renderList);
  52972. };
  52973. // public
  52974. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  52975. this._renderTexture.renderList = renderList;
  52976. };
  52977. PostProcessRenderPass.prototype.getRenderTexture = function () {
  52978. return this._renderTexture;
  52979. };
  52980. return PostProcessRenderPass;
  52981. }());
  52982. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  52983. })(BABYLON || (BABYLON = {}));
  52984. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  52985. var BABYLON;
  52986. (function (BABYLON) {
  52987. var PostProcessRenderEffect = (function () {
  52988. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  52989. this._engine = engine;
  52990. this._name = name;
  52991. this._singleInstance = singleInstance || true;
  52992. this._getPostProcess = getPostProcess;
  52993. this._cameras = [];
  52994. this._indicesForCamera = [];
  52995. this._postProcesses = {};
  52996. this._renderPasses = {};
  52997. this._renderEffectAsPasses = {};
  52998. }
  52999. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  53000. get: function () {
  53001. for (var index in this._postProcesses) {
  53002. if (!this._postProcesses[index].isSupported) {
  53003. return false;
  53004. }
  53005. }
  53006. return true;
  53007. },
  53008. enumerable: true,
  53009. configurable: true
  53010. });
  53011. PostProcessRenderEffect.prototype._update = function () {
  53012. for (var renderPassName in this._renderPasses) {
  53013. this._renderPasses[renderPassName]._update();
  53014. }
  53015. };
  53016. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  53017. this._renderPasses[renderPass._name] = renderPass;
  53018. this._linkParameters();
  53019. };
  53020. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  53021. delete this._renderPasses[renderPass._name];
  53022. this._linkParameters();
  53023. };
  53024. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  53025. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  53026. this._linkParameters();
  53027. };
  53028. PostProcessRenderEffect.prototype.getPass = function (passName) {
  53029. for (var renderPassName in this._renderPasses) {
  53030. if (renderPassName === passName) {
  53031. return this._renderPasses[passName];
  53032. }
  53033. }
  53034. };
  53035. PostProcessRenderEffect.prototype.emptyPasses = function () {
  53036. this._renderPasses = {};
  53037. this._linkParameters();
  53038. };
  53039. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  53040. var cameraKey;
  53041. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53042. for (var i = 0; i < _cam.length; i++) {
  53043. var camera = _cam[i];
  53044. var cameraName = camera.name;
  53045. if (this._singleInstance) {
  53046. cameraKey = 0;
  53047. }
  53048. else {
  53049. cameraKey = cameraName;
  53050. }
  53051. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  53052. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  53053. if (!this._indicesForCamera[cameraName]) {
  53054. this._indicesForCamera[cameraName] = [];
  53055. }
  53056. this._indicesForCamera[cameraName].push(index);
  53057. if (this._cameras.indexOf(camera) === -1) {
  53058. this._cameras[cameraName] = camera;
  53059. }
  53060. for (var passName in this._renderPasses) {
  53061. this._renderPasses[passName]._incRefCount();
  53062. }
  53063. }
  53064. this._linkParameters();
  53065. };
  53066. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  53067. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53068. for (var i = 0; i < _cam.length; i++) {
  53069. var camera = _cam[i];
  53070. var cameraName = camera.name;
  53071. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  53072. var index = this._cameras.indexOf(cameraName);
  53073. this._indicesForCamera.splice(index, 1);
  53074. this._cameras.splice(index, 1);
  53075. for (var passName in this._renderPasses) {
  53076. this._renderPasses[passName]._decRefCount();
  53077. }
  53078. }
  53079. };
  53080. PostProcessRenderEffect.prototype._enable = function (cameras) {
  53081. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53082. for (var i = 0; i < _cam.length; i++) {
  53083. var camera = _cam[i];
  53084. var cameraName = camera.name;
  53085. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  53086. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  53087. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  53088. }
  53089. }
  53090. for (var passName in this._renderPasses) {
  53091. this._renderPasses[passName]._incRefCount();
  53092. }
  53093. }
  53094. };
  53095. PostProcessRenderEffect.prototype._disable = function (cameras) {
  53096. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53097. for (var i = 0; i < _cam.length; i++) {
  53098. var camera = _cam[i];
  53099. var cameraName = camera.Name;
  53100. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  53101. for (var passName in this._renderPasses) {
  53102. this._renderPasses[passName]._decRefCount();
  53103. }
  53104. }
  53105. };
  53106. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  53107. if (this._singleInstance) {
  53108. return this._postProcesses[0];
  53109. }
  53110. else {
  53111. return this._postProcesses[camera.name];
  53112. }
  53113. };
  53114. PostProcessRenderEffect.prototype._linkParameters = function () {
  53115. var _this = this;
  53116. for (var index in this._postProcesses) {
  53117. if (this.applyParameters) {
  53118. this.applyParameters(this._postProcesses[index]);
  53119. }
  53120. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  53121. _this._linkTextures(effect);
  53122. });
  53123. }
  53124. };
  53125. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  53126. for (var renderPassName in this._renderPasses) {
  53127. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  53128. }
  53129. for (var renderEffectName in this._renderEffectAsPasses) {
  53130. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  53131. }
  53132. };
  53133. return PostProcessRenderEffect;
  53134. }());
  53135. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  53136. })(BABYLON || (BABYLON = {}));
  53137. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  53138. var BABYLON;
  53139. (function (BABYLON) {
  53140. var PostProcessRenderPipeline = (function () {
  53141. function PostProcessRenderPipeline(engine, name) {
  53142. this._engine = engine;
  53143. this._name = name;
  53144. this._renderEffects = new Array();
  53145. this._renderEffectsForIsolatedPass = new Array();
  53146. this._cameras = [];
  53147. }
  53148. PostProcessRenderPipeline.prototype.getClassName = function () {
  53149. return "PostProcessRenderPipeline";
  53150. };
  53151. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  53152. get: function () {
  53153. for (var renderEffectName in this._renderEffects) {
  53154. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53155. if (!this._renderEffects[renderEffectName].isSupported) {
  53156. return false;
  53157. }
  53158. }
  53159. }
  53160. return true;
  53161. },
  53162. enumerable: true,
  53163. configurable: true
  53164. });
  53165. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  53166. this._renderEffects[renderEffect._name] = renderEffect;
  53167. };
  53168. // private
  53169. PostProcessRenderPipeline.prototype._rebuild = function () {
  53170. };
  53171. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  53172. var renderEffects = this._renderEffects[renderEffectName];
  53173. if (!renderEffects) {
  53174. return;
  53175. }
  53176. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  53177. };
  53178. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  53179. var renderEffects = this._renderEffects[renderEffectName];
  53180. if (!renderEffects) {
  53181. return;
  53182. }
  53183. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  53184. };
  53185. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  53186. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53187. var indicesToDelete = [];
  53188. var i;
  53189. for (i = 0; i < _cam.length; i++) {
  53190. var camera = _cam[i];
  53191. var cameraName = camera.name;
  53192. if (this._cameras.indexOf(camera) === -1) {
  53193. this._cameras[cameraName] = camera;
  53194. }
  53195. else if (unique) {
  53196. indicesToDelete.push(i);
  53197. }
  53198. }
  53199. for (i = 0; i < indicesToDelete.length; i++) {
  53200. cameras.splice(indicesToDelete[i], 1);
  53201. }
  53202. for (var renderEffectName in this._renderEffects) {
  53203. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53204. this._renderEffects[renderEffectName]._attachCameras(_cam);
  53205. }
  53206. }
  53207. };
  53208. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  53209. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53210. for (var renderEffectName in this._renderEffects) {
  53211. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53212. this._renderEffects[renderEffectName]._detachCameras(_cam);
  53213. }
  53214. }
  53215. for (var i = 0; i < _cam.length; i++) {
  53216. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  53217. }
  53218. };
  53219. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  53220. var _this = this;
  53221. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53222. var pass = null;
  53223. var renderEffectName;
  53224. for (renderEffectName in this._renderEffects) {
  53225. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53226. pass = this._renderEffects[renderEffectName].getPass(passName);
  53227. if (pass != null) {
  53228. break;
  53229. }
  53230. }
  53231. }
  53232. if (pass === null) {
  53233. return;
  53234. }
  53235. for (renderEffectName in this._renderEffects) {
  53236. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53237. this._renderEffects[renderEffectName]._disable(_cam);
  53238. }
  53239. }
  53240. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  53241. for (var i = 0; i < _cam.length; i++) {
  53242. var camera = _cam[i];
  53243. var cameraName = camera.name;
  53244. 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); });
  53245. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  53246. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  53247. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  53248. }
  53249. };
  53250. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  53251. var _this = this;
  53252. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53253. for (var i = 0; i < _cam.length; i++) {
  53254. var camera = _cam[i];
  53255. var cameraName = camera.name;
  53256. 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); });
  53257. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  53258. }
  53259. for (var renderEffectName in this._renderEffects) {
  53260. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53261. this._renderEffects[renderEffectName]._enable(_cam);
  53262. }
  53263. }
  53264. };
  53265. PostProcessRenderPipeline.prototype._update = function () {
  53266. for (var renderEffectName in this._renderEffects) {
  53267. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53268. this._renderEffects[renderEffectName]._update();
  53269. }
  53270. }
  53271. for (var i = 0; i < this._cameras.length; i++) {
  53272. var cameraName = this._cameras[i].name;
  53273. if (this._renderEffectsForIsolatedPass[cameraName]) {
  53274. this._renderEffectsForIsolatedPass[cameraName]._update();
  53275. }
  53276. }
  53277. };
  53278. PostProcessRenderPipeline.prototype._reset = function () {
  53279. this._renderEffects = new Array();
  53280. this._renderEffectsForIsolatedPass = new Array();
  53281. };
  53282. PostProcessRenderPipeline.prototype.dispose = function () {
  53283. // Must be implemented by children
  53284. };
  53285. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  53286. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  53287. __decorate([
  53288. BABYLON.serialize()
  53289. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  53290. return PostProcessRenderPipeline;
  53291. }());
  53292. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  53293. })(BABYLON || (BABYLON = {}));
  53294. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  53295. var BABYLON;
  53296. (function (BABYLON) {
  53297. var DepthRenderer = (function () {
  53298. function DepthRenderer(scene, type) {
  53299. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53300. var _this = this;
  53301. this._viewMatrix = BABYLON.Matrix.Zero();
  53302. this._projectionMatrix = BABYLON.Matrix.Zero();
  53303. this._transformMatrix = BABYLON.Matrix.Zero();
  53304. this._worldViewProjection = BABYLON.Matrix.Zero();
  53305. this._scene = scene;
  53306. var engine = scene.getEngine();
  53307. // Render target
  53308. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53309. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53310. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53311. this._depthMap.refreshRate = 1;
  53312. this._depthMap.renderParticles = false;
  53313. this._depthMap.renderList = null;
  53314. // set default depth value to 1.0 (far away)
  53315. this._depthMap.onClearObservable.add(function (engine) {
  53316. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53317. });
  53318. // Custom render function
  53319. var renderSubMesh = function (subMesh) {
  53320. var mesh = subMesh.getRenderingMesh();
  53321. var scene = _this._scene;
  53322. var engine = scene.getEngine();
  53323. // Culling
  53324. engine.setState(subMesh.getMaterial().backFaceCulling);
  53325. // Managing instances
  53326. var batch = mesh._getInstancesRenderList(subMesh._id);
  53327. if (batch.mustReturn) {
  53328. return;
  53329. }
  53330. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53331. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53332. engine.enableEffect(_this._effect);
  53333. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53334. var material = subMesh.getMaterial();
  53335. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53336. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  53337. // Alpha test
  53338. if (material && material.needAlphaTesting()) {
  53339. var alphaTexture = material.getAlphaTestTexture();
  53340. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53341. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53342. }
  53343. // Bones
  53344. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53345. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53346. }
  53347. // Draw
  53348. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53349. }
  53350. };
  53351. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53352. var index;
  53353. if (depthOnlySubMeshes.length) {
  53354. engine.setColorWrite(false);
  53355. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53356. renderSubMesh(depthOnlySubMeshes.data[index]);
  53357. }
  53358. engine.setColorWrite(true);
  53359. }
  53360. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53361. renderSubMesh(opaqueSubMeshes.data[index]);
  53362. }
  53363. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53364. renderSubMesh(alphaTestSubMeshes.data[index]);
  53365. }
  53366. };
  53367. }
  53368. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53369. var material = subMesh.getMaterial();
  53370. if (material.disableDepthWrite) {
  53371. return false;
  53372. }
  53373. var defines = [];
  53374. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53375. var mesh = subMesh.getMesh();
  53376. var scene = mesh.getScene();
  53377. // Alpha test
  53378. if (material && material.needAlphaTesting()) {
  53379. defines.push("#define ALPHATEST");
  53380. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53381. attribs.push(BABYLON.VertexBuffer.UVKind);
  53382. defines.push("#define UV1");
  53383. }
  53384. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53385. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53386. defines.push("#define UV2");
  53387. }
  53388. }
  53389. // Bones
  53390. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53391. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53392. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53393. if (mesh.numBoneInfluencers > 4) {
  53394. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53395. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53396. }
  53397. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53398. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53399. }
  53400. else {
  53401. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53402. }
  53403. // Instances
  53404. if (useInstances) {
  53405. defines.push("#define INSTANCES");
  53406. attribs.push("world0");
  53407. attribs.push("world1");
  53408. attribs.push("world2");
  53409. attribs.push("world3");
  53410. }
  53411. // Get correct effect
  53412. var join = defines.join("\n");
  53413. if (this._cachedDefines !== join) {
  53414. this._cachedDefines = join;
  53415. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  53416. }
  53417. return this._effect.isReady();
  53418. };
  53419. DepthRenderer.prototype.getDepthMap = function () {
  53420. return this._depthMap;
  53421. };
  53422. // Methods
  53423. DepthRenderer.prototype.dispose = function () {
  53424. this._depthMap.dispose();
  53425. };
  53426. return DepthRenderer;
  53427. }());
  53428. BABYLON.DepthRenderer = DepthRenderer;
  53429. })(BABYLON || (BABYLON = {}));
  53430. //# sourceMappingURL=babylon.depthRenderer.js.map
  53431. var BABYLON;
  53432. (function (BABYLON) {
  53433. var SSAORenderingPipeline = (function (_super) {
  53434. __extends(SSAORenderingPipeline, _super);
  53435. /**
  53436. * @constructor
  53437. * @param {string} name - The rendering pipeline name
  53438. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53439. * @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 }
  53440. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53441. */
  53442. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53443. var _this = _super.call(this, scene.getEngine(), name) || this;
  53444. // Members
  53445. /**
  53446. * The PassPostProcess id in the pipeline that contains the original scene color
  53447. * @type {string}
  53448. */
  53449. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53450. /**
  53451. * The SSAO PostProcess id in the pipeline
  53452. * @type {string}
  53453. */
  53454. _this.SSAORenderEffect = "SSAORenderEffect";
  53455. /**
  53456. * The horizontal blur PostProcess id in the pipeline
  53457. * @type {string}
  53458. */
  53459. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53460. /**
  53461. * The vertical blur PostProcess id in the pipeline
  53462. * @type {string}
  53463. */
  53464. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53465. /**
  53466. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53467. * @type {string}
  53468. */
  53469. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53470. /**
  53471. * The output strength of the SSAO post-process. Default value is 1.0.
  53472. * @type {number}
  53473. */
  53474. _this.totalStrength = 1.0;
  53475. /**
  53476. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53477. * @type {number}
  53478. */
  53479. _this.radius = 0.0001;
  53480. /**
  53481. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53482. * Must not be equal to fallOff and superior to fallOff.
  53483. * Default value is 0.975
  53484. * @type {number}
  53485. */
  53486. _this.area = 0.0075;
  53487. /**
  53488. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53489. * Must not be equal to area and inferior to area.
  53490. * Default value is 0.0
  53491. * @type {number}
  53492. */
  53493. _this.fallOff = 0.000001;
  53494. /**
  53495. * The base color of the SSAO post-process
  53496. * The final result is "base + ssao" between [0, 1]
  53497. * @type {number}
  53498. */
  53499. _this.base = 0.5;
  53500. _this._firstUpdate = true;
  53501. _this._scene = scene;
  53502. // Set up assets
  53503. _this._createRandomTexture();
  53504. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53505. var ssaoRatio = ratio.ssaoRatio || ratio;
  53506. var combineRatio = ratio.combineRatio || ratio;
  53507. _this._ratio = {
  53508. ssaoRatio: ssaoRatio,
  53509. combineRatio: combineRatio
  53510. };
  53511. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53512. _this._createSSAOPostProcess(ssaoRatio);
  53513. _this._createBlurPostProcess(ssaoRatio);
  53514. _this._createSSAOCombinePostProcess(combineRatio);
  53515. // Set up pipeline
  53516. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53517. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53518. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53519. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53520. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53521. // Finish
  53522. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53523. if (cameras)
  53524. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53525. return _this;
  53526. }
  53527. // Public Methods
  53528. /**
  53529. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53530. */
  53531. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53532. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53533. for (var i = 0; i < this._scene.cameras.length; i++) {
  53534. var camera = this._scene.cameras[i];
  53535. this._originalColorPostProcess.dispose(camera);
  53536. this._ssaoPostProcess.dispose(camera);
  53537. this._blurHPostProcess.dispose(camera);
  53538. this._blurVPostProcess.dispose(camera);
  53539. this._ssaoCombinePostProcess.dispose(camera);
  53540. }
  53541. this._randomTexture.dispose();
  53542. if (disableDepthRender)
  53543. this._scene.disableDepthRenderer();
  53544. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53545. _super.prototype.dispose.call(this);
  53546. };
  53547. // Private Methods
  53548. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53549. var _this = this;
  53550. /*
  53551. var samplerOffsets = [
  53552. -8.0, -6.0, -4.0, -2.0,
  53553. 0.0,
  53554. 2.0, 4.0, 6.0, 8.0
  53555. ];
  53556. */
  53557. var samples = 16;
  53558. var samplerOffsets = [];
  53559. for (var i = -8; i < 8; i++) {
  53560. samplerOffsets.push(i * 2);
  53561. }
  53562. 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");
  53563. this._blurHPostProcess.onApply = function (effect) {
  53564. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53565. effect.setTexture("depthSampler", _this._depthTexture);
  53566. if (_this._firstUpdate) {
  53567. effect.setArray("samplerOffsets", samplerOffsets);
  53568. }
  53569. };
  53570. 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");
  53571. this._blurVPostProcess.onApply = function (effect) {
  53572. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53573. effect.setTexture("depthSampler", _this._depthTexture);
  53574. if (_this._firstUpdate) {
  53575. effect.setArray("samplerOffsets", samplerOffsets);
  53576. _this._firstUpdate = false;
  53577. }
  53578. };
  53579. };
  53580. SSAORenderingPipeline.prototype._rebuild = function () {
  53581. this._firstUpdate = true;
  53582. _super.prototype._rebuild.call(this);
  53583. };
  53584. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53585. var _this = this;
  53586. var numSamples = 16;
  53587. var sampleSphere = [
  53588. 0.5381, 0.1856, -0.4319,
  53589. 0.1379, 0.2486, 0.4430,
  53590. 0.3371, 0.5679, -0.0057,
  53591. -0.6999, -0.0451, -0.0019,
  53592. 0.0689, -0.1598, -0.8547,
  53593. 0.0560, 0.0069, -0.1843,
  53594. -0.0146, 0.1402, 0.0762,
  53595. 0.0100, -0.1924, -0.0344,
  53596. -0.3577, -0.5301, -0.4358,
  53597. -0.3169, 0.1063, 0.0158,
  53598. 0.0103, -0.5869, 0.0046,
  53599. -0.0897, -0.4940, 0.3287,
  53600. 0.7119, -0.0154, -0.0918,
  53601. -0.0533, 0.0596, -0.5411,
  53602. 0.0352, -0.0631, 0.5460,
  53603. -0.4776, 0.2847, -0.0271
  53604. ];
  53605. var samplesFactor = 1.0 / numSamples;
  53606. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53607. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53608. "area", "fallOff", "base", "range", "viewport"
  53609. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53610. var viewport = new BABYLON.Vector2(0, 0);
  53611. this._ssaoPostProcess.onApply = function (effect) {
  53612. if (_this._firstUpdate) {
  53613. effect.setArray3("sampleSphere", sampleSphere);
  53614. effect.setFloat("samplesFactor", samplesFactor);
  53615. effect.setFloat("randTextureTiles", 4.0);
  53616. }
  53617. effect.setFloat("totalStrength", _this.totalStrength);
  53618. effect.setFloat("radius", _this.radius);
  53619. effect.setFloat("area", _this.area);
  53620. effect.setFloat("fallOff", _this.fallOff);
  53621. effect.setFloat("base", _this.base);
  53622. effect.setTexture("textureSampler", _this._depthTexture);
  53623. effect.setTexture("randomSampler", _this._randomTexture);
  53624. };
  53625. };
  53626. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53627. var _this = this;
  53628. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53629. this._ssaoCombinePostProcess.onApply = function (effect) {
  53630. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53631. };
  53632. };
  53633. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53634. var size = 512;
  53635. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53636. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53637. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53638. var context = this._randomTexture.getContext();
  53639. var rand = function (min, max) {
  53640. return Math.random() * (max - min) + min;
  53641. };
  53642. var randVector = BABYLON.Vector3.Zero();
  53643. for (var x = 0; x < size; x++) {
  53644. for (var y = 0; y < size; y++) {
  53645. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53646. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53647. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53648. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53649. context.fillRect(x, y, 1, 1);
  53650. }
  53651. }
  53652. this._randomTexture.update(false);
  53653. };
  53654. __decorate([
  53655. BABYLON.serialize()
  53656. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53657. __decorate([
  53658. BABYLON.serialize()
  53659. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53660. __decorate([
  53661. BABYLON.serialize()
  53662. ], SSAORenderingPipeline.prototype, "area", void 0);
  53663. __decorate([
  53664. BABYLON.serialize()
  53665. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53666. __decorate([
  53667. BABYLON.serialize()
  53668. ], SSAORenderingPipeline.prototype, "base", void 0);
  53669. __decorate([
  53670. BABYLON.serialize()
  53671. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53672. return SSAORenderingPipeline;
  53673. }(BABYLON.PostProcessRenderPipeline));
  53674. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53675. })(BABYLON || (BABYLON = {}));
  53676. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  53677. var BABYLON;
  53678. (function (BABYLON) {
  53679. var SSAO2RenderingPipeline = (function (_super) {
  53680. __extends(SSAO2RenderingPipeline, _super);
  53681. /**
  53682. * @constructor
  53683. * @param {string} name - The rendering pipeline name
  53684. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53685. * @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 }
  53686. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53687. */
  53688. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  53689. var _this = _super.call(this, scene.getEngine(), name) || this;
  53690. // Members
  53691. /**
  53692. * The PassPostProcess id in the pipeline that contains the original scene color
  53693. * @type {string}
  53694. */
  53695. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53696. /**
  53697. * The SSAO PostProcess id in the pipeline
  53698. * @type {string}
  53699. */
  53700. _this.SSAORenderEffect = "SSAORenderEffect";
  53701. /**
  53702. * The horizontal blur PostProcess id in the pipeline
  53703. * @type {string}
  53704. */
  53705. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53706. /**
  53707. * The vertical blur PostProcess id in the pipeline
  53708. * @type {string}
  53709. */
  53710. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53711. /**
  53712. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53713. * @type {string}
  53714. */
  53715. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53716. /**
  53717. * The output strength of the SSAO post-process. Default value is 1.0.
  53718. * @type {number}
  53719. */
  53720. _this.totalStrength = 1.0;
  53721. /**
  53722. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  53723. * @type {number}
  53724. */
  53725. _this.maxZ = 100.0;
  53726. /**
  53727. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  53728. * @type {number}
  53729. */
  53730. _this.minZAspect = 0.2;
  53731. /**
  53732. * Number of samples used for the SSAO calculations. Default value is 8
  53733. * @type {number}
  53734. */
  53735. _this._samples = 8;
  53736. /**
  53737. * Are we using bilateral blur ?
  53738. * @type {boolean}
  53739. */
  53740. _this._expensiveBlur = true;
  53741. /**
  53742. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  53743. * @type {number}
  53744. */
  53745. _this.radius = 2.0;
  53746. /**
  53747. * The base color of the SSAO post-process
  53748. * The final result is "base + ssao" between [0, 1]
  53749. * @type {number}
  53750. */
  53751. _this.base = 0.1;
  53752. _this._firstUpdate = true;
  53753. _this._scene = scene;
  53754. if (!_this.isSupported) {
  53755. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  53756. return _this;
  53757. }
  53758. var ssaoRatio = ratio.ssaoRatio || ratio;
  53759. var blurRatio = ratio.blurRatio || ratio;
  53760. _this._ratio = {
  53761. ssaoRatio: ssaoRatio,
  53762. blurRatio: blurRatio
  53763. };
  53764. // Set up assets
  53765. _this._createRandomTexture();
  53766. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  53767. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  53768. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53769. _this._createSSAOPostProcess(1.0);
  53770. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  53771. _this._createSSAOCombinePostProcess(blurRatio);
  53772. // Set up pipeline
  53773. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53774. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53775. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53776. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53777. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53778. // Finish
  53779. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53780. if (cameras)
  53781. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53782. return _this;
  53783. }
  53784. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  53785. get: function () {
  53786. return this._samples;
  53787. },
  53788. set: function (n) {
  53789. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  53790. this._samples = n;
  53791. this._sampleSphere = this._generateHemisphere();
  53792. this._firstUpdate = true;
  53793. },
  53794. enumerable: true,
  53795. configurable: true
  53796. });
  53797. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  53798. get: function () {
  53799. return this._expensiveBlur;
  53800. },
  53801. set: function (b) {
  53802. 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"]);
  53803. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  53804. this._expensiveBlur = b;
  53805. this._firstUpdate = true;
  53806. },
  53807. enumerable: true,
  53808. configurable: true
  53809. });
  53810. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  53811. /**
  53812. * Support test.
  53813. * @type {boolean}
  53814. */
  53815. get: function () {
  53816. var engine = BABYLON.Engine.LastCreatedEngine;
  53817. return engine.getCaps().drawBuffersExtension;
  53818. },
  53819. enumerable: true,
  53820. configurable: true
  53821. });
  53822. // Public Methods
  53823. /**
  53824. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53825. */
  53826. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  53827. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  53828. for (var i = 0; i < this._scene.cameras.length; i++) {
  53829. var camera = this._scene.cameras[i];
  53830. this._originalColorPostProcess.dispose(camera);
  53831. this._ssaoPostProcess.dispose(camera);
  53832. this._blurHPostProcess.dispose(camera);
  53833. this._blurVPostProcess.dispose(camera);
  53834. this._ssaoCombinePostProcess.dispose(camera);
  53835. }
  53836. this._randomTexture.dispose();
  53837. if (disableGeometryBufferRenderer)
  53838. this._scene.disableGeometryBufferRenderer();
  53839. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53840. _super.prototype.dispose.call(this);
  53841. };
  53842. // Private Methods
  53843. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  53844. var _this = this;
  53845. var samples = 16;
  53846. this._samplerOffsets = [];
  53847. var expensive = this.expensiveBlur;
  53848. for (var i = -8; i < 8; i++) {
  53849. this._samplerOffsets.push(i * 2 + 0.5);
  53850. }
  53851. 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");
  53852. this._blurHPostProcess.onApply = function (effect) {
  53853. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53854. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53855. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53856. effect.setFloat("radius", _this.radius);
  53857. effect.setTexture("depthSampler", _this._depthTexture);
  53858. if (_this._firstUpdate) {
  53859. effect.setArray("samplerOffsets", _this._samplerOffsets);
  53860. }
  53861. };
  53862. 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");
  53863. this._blurVPostProcess.onApply = function (effect) {
  53864. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53865. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53866. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53867. effect.setFloat("radius", _this.radius);
  53868. effect.setTexture("depthSampler", _this._depthTexture);
  53869. if (_this._firstUpdate) {
  53870. effect.setArray("samplerOffsets", _this._samplerOffsets);
  53871. _this._firstUpdate = false;
  53872. }
  53873. };
  53874. };
  53875. SSAO2RenderingPipeline.prototype._rebuild = function () {
  53876. this._firstUpdate = true;
  53877. _super.prototype._rebuild.call(this);
  53878. };
  53879. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  53880. var numSamples = this.samples;
  53881. var result = [];
  53882. var vector, scale;
  53883. var rand = function (min, max) {
  53884. return Math.random() * (max - min) + min;
  53885. };
  53886. var lerp = function (start, end, percent) {
  53887. return (start + percent * (end - start));
  53888. };
  53889. var i = 0;
  53890. var normal = new BABYLON.Vector3(0, 0, 1);
  53891. while (i < numSamples) {
  53892. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  53893. vector.normalize();
  53894. scale = i / numSamples;
  53895. scale = lerp(0.1, 1.0, scale * scale);
  53896. vector.scaleInPlace(scale);
  53897. result.push(vector.x, vector.y, vector.z);
  53898. i++;
  53899. }
  53900. return result;
  53901. };
  53902. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53903. var _this = this;
  53904. var numSamples = this.samples;
  53905. this._sampleSphere = this._generateHemisphere();
  53906. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  53907. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53908. "base", "range", "projection", "near", "far", "texelSize",
  53909. "xViewport", "yViewport", "maxZ", "minZAspect"
  53910. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53911. this._ssaoPostProcess.onApply = function (effect) {
  53912. if (_this._firstUpdate) {
  53913. effect.setArray3("sampleSphere", _this._sampleSphere);
  53914. effect.setFloat("randTextureTiles", 4.0);
  53915. }
  53916. effect.setFloat("samplesFactor", 1 / _this.samples);
  53917. effect.setFloat("totalStrength", _this.totalStrength);
  53918. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  53919. effect.setFloat("radius", _this.radius);
  53920. effect.setFloat("maxZ", _this.maxZ);
  53921. effect.setFloat("minZAspect", _this.minZAspect);
  53922. effect.setFloat("base", _this.base);
  53923. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53924. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53925. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  53926. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  53927. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  53928. effect.setTexture("textureSampler", _this._depthTexture);
  53929. effect.setTexture("normalSampler", _this._normalTexture);
  53930. effect.setTexture("randomSampler", _this._randomTexture);
  53931. };
  53932. };
  53933. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53934. var _this = this;
  53935. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53936. this._ssaoCombinePostProcess.onApply = function (effect) {
  53937. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53938. };
  53939. };
  53940. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  53941. var size = 512;
  53942. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53943. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53944. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53945. var context = this._randomTexture.getContext();
  53946. var rand = function (min, max) {
  53947. return Math.random() * (max - min) + min;
  53948. };
  53949. var randVector = BABYLON.Vector3.Zero();
  53950. for (var x = 0; x < size; x++) {
  53951. for (var y = 0; y < size; y++) {
  53952. randVector.x = rand(0.0, 1.0);
  53953. randVector.y = rand(0.0, 1.0);
  53954. randVector.z = 0.0;
  53955. randVector.normalize();
  53956. randVector.scaleInPlace(255);
  53957. randVector.x = Math.floor(randVector.x);
  53958. randVector.y = Math.floor(randVector.y);
  53959. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53960. context.fillRect(x, y, 1, 1);
  53961. }
  53962. }
  53963. this._randomTexture.update(false);
  53964. };
  53965. __decorate([
  53966. BABYLON.serialize()
  53967. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  53968. __decorate([
  53969. BABYLON.serialize()
  53970. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  53971. __decorate([
  53972. BABYLON.serialize()
  53973. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  53974. __decorate([
  53975. BABYLON.serialize("samples")
  53976. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  53977. __decorate([
  53978. BABYLON.serialize("expensiveBlur")
  53979. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  53980. __decorate([
  53981. BABYLON.serialize()
  53982. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  53983. __decorate([
  53984. BABYLON.serialize()
  53985. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  53986. __decorate([
  53987. BABYLON.serialize()
  53988. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  53989. return SSAO2RenderingPipeline;
  53990. }(BABYLON.PostProcessRenderPipeline));
  53991. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  53992. })(BABYLON || (BABYLON = {}));
  53993. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  53994. // BABYLON.JS Chromatic Aberration GLSL Shader
  53995. // Author: Olivier Guyot
  53996. // Separates very slightly R, G and B colors on the edges of the screen
  53997. // Inspired by Francois Tarlier & Martins Upitis
  53998. var BABYLON;
  53999. (function (BABYLON) {
  54000. var LensRenderingPipeline = (function (_super) {
  54001. __extends(LensRenderingPipeline, _super);
  54002. /**
  54003. * @constructor
  54004. *
  54005. * Effect parameters are as follow:
  54006. * {
  54007. * chromatic_aberration: number; // from 0 to x (1 for realism)
  54008. * edge_blur: number; // from 0 to x (1 for realism)
  54009. * distortion: number; // from 0 to x (1 for realism)
  54010. * grain_amount: number; // from 0 to 1
  54011. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  54012. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  54013. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  54014. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  54015. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  54016. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  54017. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  54018. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  54019. * }
  54020. * Note: if an effect parameter is unset, effect is disabled
  54021. *
  54022. * @param {string} name - The rendering pipeline name
  54023. * @param {object} parameters - An object containing all parameters (see above)
  54024. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54025. * @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)
  54026. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54027. */
  54028. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  54029. if (ratio === void 0) { ratio = 1.0; }
  54030. var _this = _super.call(this, scene.getEngine(), name) || this;
  54031. // Lens effects can be of the following:
  54032. // - chromatic aberration (slight shift of RGB colors)
  54033. // - blur on the edge of the lens
  54034. // - lens distortion
  54035. // - depth-of-field blur & highlights enhancing
  54036. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  54037. // - grain effect (noise or custom texture)
  54038. // Two additional texture samplers are needed:
  54039. // - depth map (for depth-of-field)
  54040. // - grain texture
  54041. /**
  54042. * The chromatic aberration PostProcess id in the pipeline
  54043. * @type {string}
  54044. */
  54045. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  54046. /**
  54047. * The highlights enhancing PostProcess id in the pipeline
  54048. * @type {string}
  54049. */
  54050. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  54051. /**
  54052. * The depth-of-field PostProcess id in the pipeline
  54053. * @type {string}
  54054. */
  54055. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  54056. _this._scene = scene;
  54057. // Fetch texture samplers
  54058. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54059. if (parameters.grain_texture) {
  54060. _this._grainTexture = parameters.grain_texture;
  54061. }
  54062. else {
  54063. _this._createGrainTexture();
  54064. }
  54065. // save parameters
  54066. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  54067. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  54068. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  54069. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  54070. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  54071. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  54072. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  54073. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  54074. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  54075. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  54076. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  54077. // Create effects
  54078. _this._createChromaticAberrationPostProcess(ratio);
  54079. _this._createHighlightsPostProcess(ratio);
  54080. _this._createDepthOfFieldPostProcess(ratio / 4);
  54081. // Set up pipeline
  54082. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  54083. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  54084. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  54085. if (_this._highlightsGain === -1) {
  54086. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  54087. }
  54088. // Finish
  54089. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54090. if (cameras) {
  54091. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54092. }
  54093. return _this;
  54094. }
  54095. // public methods (self explanatory)
  54096. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  54097. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  54098. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  54099. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  54100. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  54101. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  54102. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  54103. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  54104. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  54105. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  54106. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  54107. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  54108. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  54109. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  54110. };
  54111. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  54112. this._highlightsPostProcess.updateEffect();
  54113. };
  54114. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  54115. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  54116. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  54117. this._highlightsGain = amount;
  54118. };
  54119. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  54120. if (this._highlightsGain === -1) {
  54121. this._highlightsGain = 1.0;
  54122. }
  54123. this._highlightsThreshold = amount;
  54124. };
  54125. LensRenderingPipeline.prototype.disableHighlights = function () {
  54126. this._highlightsGain = -1;
  54127. };
  54128. /**
  54129. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  54130. */
  54131. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54132. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54133. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54134. this._chromaticAberrationPostProcess = undefined;
  54135. this._highlightsPostProcess = undefined;
  54136. this._depthOfFieldPostProcess = undefined;
  54137. this._grainTexture.dispose();
  54138. if (disableDepthRender)
  54139. this._scene.disableDepthRenderer();
  54140. };
  54141. // colors shifting and distortion
  54142. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  54143. var _this = this;
  54144. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  54145. [], // samplers
  54146. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54147. this._chromaticAberrationPostProcess.onApply = function (effect) {
  54148. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  54149. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54150. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54151. };
  54152. };
  54153. // highlights enhancing
  54154. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  54155. var _this = this;
  54156. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  54157. [], // samplers
  54158. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  54159. this._highlightsPostProcess.onApply = function (effect) {
  54160. effect.setFloat('gain', _this._highlightsGain);
  54161. effect.setFloat('threshold', _this._highlightsThreshold);
  54162. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  54163. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54164. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54165. };
  54166. };
  54167. // colors shifting and distortion
  54168. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  54169. var _this = this;
  54170. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  54171. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  54172. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  54173. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54174. this._depthOfFieldPostProcess.onApply = function (effect) {
  54175. effect.setTexture("depthSampler", _this._depthTexture);
  54176. effect.setTexture("grainSampler", _this._grainTexture);
  54177. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54178. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54179. effect.setFloat('grain_amount', _this._grainAmount);
  54180. effect.setBool('blur_noise', _this._blurNoise);
  54181. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54182. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54183. effect.setFloat('distortion', _this._distortion);
  54184. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54185. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54186. effect.setFloat('aperture', _this._dofAperture);
  54187. effect.setFloat('darken', _this._dofDarken);
  54188. effect.setFloat('edge_blur', _this._edgeBlur);
  54189. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54190. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54191. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54192. };
  54193. };
  54194. // creates a black and white random noise texture, 512x512
  54195. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54196. var size = 512;
  54197. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54198. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54199. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54200. var context = this._grainTexture.getContext();
  54201. var rand = function (min, max) {
  54202. return Math.random() * (max - min) + min;
  54203. };
  54204. var value;
  54205. for (var x = 0; x < size; x++) {
  54206. for (var y = 0; y < size; y++) {
  54207. value = Math.floor(rand(0.42, 0.58) * 255);
  54208. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54209. context.fillRect(x, y, 1, 1);
  54210. }
  54211. }
  54212. this._grainTexture.update(false);
  54213. };
  54214. return LensRenderingPipeline;
  54215. }(BABYLON.PostProcessRenderPipeline));
  54216. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54217. })(BABYLON || (BABYLON = {}));
  54218. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  54219. var BABYLON;
  54220. (function (BABYLON) {
  54221. var StandardRenderingPipeline = (function (_super) {
  54222. __extends(StandardRenderingPipeline, _super);
  54223. /**
  54224. * @constructor
  54225. * @param {string} name - The rendering pipeline name
  54226. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54227. * @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)
  54228. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54229. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54230. */
  54231. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54232. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54233. var _this = _super.call(this, scene.getEngine(), name) || this;
  54234. _this.downSampleX4PostProcess = null;
  54235. _this.brightPassPostProcess = null;
  54236. _this.blurHPostProcesses = [];
  54237. _this.blurVPostProcesses = [];
  54238. _this.textureAdderPostProcess = null;
  54239. _this.volumetricLightPostProcess = null;
  54240. _this.volumetricLightSmoothXPostProcess = null;
  54241. _this.volumetricLightSmoothYPostProcess = null;
  54242. _this.volumetricLightMergePostProces = null;
  54243. _this.volumetricLightFinalPostProcess = null;
  54244. _this.luminancePostProcess = null;
  54245. _this.luminanceDownSamplePostProcesses = [];
  54246. _this.hdrPostProcess = null;
  54247. _this.textureAdderFinalPostProcess = null;
  54248. _this.lensFlareFinalPostProcess = null;
  54249. _this.hdrFinalPostProcess = null;
  54250. _this.lensFlarePostProcess = null;
  54251. _this.lensFlareComposePostProcess = null;
  54252. _this.motionBlurPostProcess = null;
  54253. _this.depthOfFieldPostProcess = null;
  54254. // Values
  54255. _this.brightThreshold = 1.0;
  54256. _this.blurWidth = 512.0;
  54257. _this.horizontalBlur = false;
  54258. _this.exposure = 1.0;
  54259. _this.lensTexture = null;
  54260. _this.volumetricLightCoefficient = 0.2;
  54261. _this.volumetricLightPower = 4.0;
  54262. _this.volumetricLightBlurScale = 64.0;
  54263. _this.sourceLight = null;
  54264. _this.hdrMinimumLuminance = 1.0;
  54265. _this.hdrDecreaseRate = 0.5;
  54266. _this.hdrIncreaseRate = 0.5;
  54267. _this.lensColorTexture = null;
  54268. _this.lensFlareStrength = 20.0;
  54269. _this.lensFlareGhostDispersal = 1.4;
  54270. _this.lensFlareHaloWidth = 0.7;
  54271. _this.lensFlareDistortionStrength = 16.0;
  54272. _this.lensStarTexture = null;
  54273. _this.lensFlareDirtTexture = null;
  54274. _this.depthOfFieldDistance = 10.0;
  54275. _this.depthOfFieldBlurWidth = 64.0;
  54276. _this.motionStrength = 1.0;
  54277. // IAnimatable
  54278. _this.animations = [];
  54279. _this._currentDepthOfFieldSource = null;
  54280. _this._hdrCurrentLuminance = 1.0;
  54281. // Getters and setters
  54282. _this._bloomEnabled = true;
  54283. _this._depthOfFieldEnabled = false;
  54284. _this._vlsEnabled = false;
  54285. _this._lensFlareEnabled = false;
  54286. _this._hdrEnabled = false;
  54287. _this._motionBlurEnabled = false;
  54288. _this._motionBlurSamples = 64.0;
  54289. _this._volumetricLightStepsCount = 50.0;
  54290. _this._cameras = cameras || [];
  54291. // Initialize
  54292. _this._scene = scene;
  54293. _this._basePostProcess = originalPostProcess;
  54294. _this._ratio = ratio;
  54295. // Misc
  54296. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54297. // Finish
  54298. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54299. _this._buildPipeline();
  54300. return _this;
  54301. }
  54302. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  54303. get: function () {
  54304. return this._bloomEnabled;
  54305. },
  54306. set: function (enabled) {
  54307. if (this._bloomEnabled === enabled) {
  54308. return;
  54309. }
  54310. this._bloomEnabled = enabled;
  54311. this._buildPipeline();
  54312. },
  54313. enumerable: true,
  54314. configurable: true
  54315. });
  54316. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54317. get: function () {
  54318. return this._depthOfFieldEnabled;
  54319. },
  54320. set: function (enabled) {
  54321. if (this._depthOfFieldEnabled === enabled) {
  54322. return;
  54323. }
  54324. this._depthOfFieldEnabled = enabled;
  54325. this._buildPipeline();
  54326. },
  54327. enumerable: true,
  54328. configurable: true
  54329. });
  54330. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54331. get: function () {
  54332. return this._lensFlareEnabled;
  54333. },
  54334. set: function (enabled) {
  54335. if (this._lensFlareEnabled === enabled) {
  54336. return;
  54337. }
  54338. this._lensFlareEnabled = enabled;
  54339. this._buildPipeline();
  54340. },
  54341. enumerable: true,
  54342. configurable: true
  54343. });
  54344. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  54345. get: function () {
  54346. return this._hdrEnabled;
  54347. },
  54348. set: function (enabled) {
  54349. if (this._hdrEnabled === enabled) {
  54350. return;
  54351. }
  54352. this._hdrEnabled = enabled;
  54353. this._buildPipeline();
  54354. },
  54355. enumerable: true,
  54356. configurable: true
  54357. });
  54358. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  54359. get: function () {
  54360. return this._vlsEnabled;
  54361. },
  54362. set: function (enabled) {
  54363. if (this._vlsEnabled === enabled) {
  54364. return;
  54365. }
  54366. if (enabled) {
  54367. var geometry = this._scene.enableGeometryBufferRenderer();
  54368. if (!geometry) {
  54369. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  54370. return;
  54371. }
  54372. }
  54373. this._vlsEnabled = enabled;
  54374. this._buildPipeline();
  54375. },
  54376. enumerable: true,
  54377. configurable: true
  54378. });
  54379. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  54380. get: function () {
  54381. return this._motionBlurEnabled;
  54382. },
  54383. set: function (enabled) {
  54384. if (this._motionBlurEnabled === enabled) {
  54385. return;
  54386. }
  54387. this._motionBlurEnabled = enabled;
  54388. this._buildPipeline();
  54389. },
  54390. enumerable: true,
  54391. configurable: true
  54392. });
  54393. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  54394. get: function () {
  54395. return this._volumetricLightStepsCount;
  54396. },
  54397. set: function (count) {
  54398. if (this.volumetricLightPostProcess) {
  54399. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  54400. }
  54401. this._volumetricLightStepsCount = count;
  54402. },
  54403. enumerable: true,
  54404. configurable: true
  54405. });
  54406. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  54407. get: function () {
  54408. return this._motionBlurSamples;
  54409. },
  54410. set: function (samples) {
  54411. if (this.motionBlurPostProcess) {
  54412. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  54413. }
  54414. this._motionBlurSamples = samples;
  54415. },
  54416. enumerable: true,
  54417. configurable: true
  54418. });
  54419. StandardRenderingPipeline.prototype._buildPipeline = function () {
  54420. var _this = this;
  54421. var ratio = this._ratio;
  54422. var scene = this._scene;
  54423. this._disposePostProcesses();
  54424. this._reset();
  54425. // Create pass post-process
  54426. if (!this._basePostProcess) {
  54427. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  54428. this.originalPostProcess.onApply = function (effect) {
  54429. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  54430. };
  54431. }
  54432. else {
  54433. this.originalPostProcess = this._basePostProcess;
  54434. }
  54435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54436. this._currentDepthOfFieldSource = this.originalPostProcess;
  54437. if (this._vlsEnabled) {
  54438. // Create volumetric light
  54439. this._createVolumetricLightPostProcess(scene, ratio);
  54440. // Create volumetric light final post-process
  54441. 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);
  54442. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  54443. }
  54444. if (this._bloomEnabled) {
  54445. // Create down sample X4 post-process
  54446. this._createDownSampleX4PostProcess(scene, ratio / 2);
  54447. // Create bright pass post-process
  54448. this._createBrightPassPostProcess(scene, ratio / 2);
  54449. // Create gaussian blur post-processes (down sampling blurs)
  54450. this._createBlurPostProcesses(scene, ratio / 4, 1);
  54451. // Create texture adder post-process
  54452. this._createTextureAdderPostProcess(scene, ratio);
  54453. // Create depth-of-field source post-process
  54454. 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);
  54455. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54456. }
  54457. if (this._lensFlareEnabled) {
  54458. // Create lens flare post-process
  54459. this._createLensFlarePostProcess(scene, ratio);
  54460. // Create depth-of-field source post-process post lens-flare and disable it now
  54461. 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);
  54462. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  54463. }
  54464. if (this._hdrEnabled) {
  54465. // Create luminance
  54466. this._createLuminancePostProcesses(scene, this._floatTextureType);
  54467. // Create HDR
  54468. this._createHdrPostProcess(scene, ratio);
  54469. // Create depth-of-field source post-process post hdr and disable it now
  54470. 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);
  54471. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  54472. }
  54473. if (this._depthOfFieldEnabled) {
  54474. // Create gaussian blur used by depth-of-field
  54475. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  54476. // Create depth-of-field post-process
  54477. this._createDepthOfFieldPostProcess(scene, ratio);
  54478. }
  54479. if (this._motionBlurEnabled) {
  54480. // Create motion blur post-process
  54481. this._createMotionBlurPostProcess(scene, ratio);
  54482. }
  54483. if (this._cameras !== null) {
  54484. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  54485. }
  54486. };
  54487. // Down Sample X4 Post-Processs
  54488. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54489. var _this = this;
  54490. var downSampleX4Offsets = new Array(32);
  54491. 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);
  54492. this.downSampleX4PostProcess.onApply = function (effect) {
  54493. var id = 0;
  54494. for (var i = -2; i < 2; i++) {
  54495. for (var j = -2; j < 2; j++) {
  54496. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54497. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54498. id += 2;
  54499. }
  54500. }
  54501. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54502. };
  54503. // Add to pipeline
  54504. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54505. };
  54506. // Brightpass Post-Process
  54507. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54508. var _this = this;
  54509. var brightOffsets = new Array(8);
  54510. 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);
  54511. this.brightPassPostProcess.onApply = function (effect) {
  54512. var sU = (1.0 / _this.brightPassPostProcess.width);
  54513. var sV = (1.0 / _this.brightPassPostProcess.height);
  54514. brightOffsets[0] = -0.5 * sU;
  54515. brightOffsets[1] = 0.5 * sV;
  54516. brightOffsets[2] = 0.5 * sU;
  54517. brightOffsets[3] = 0.5 * sV;
  54518. brightOffsets[4] = -0.5 * sU;
  54519. brightOffsets[5] = -0.5 * sV;
  54520. brightOffsets[6] = 0.5 * sU;
  54521. brightOffsets[7] = -0.5 * sV;
  54522. effect.setArray2("dsOffsets", brightOffsets);
  54523. effect.setFloat("brightThreshold", _this.brightThreshold);
  54524. };
  54525. // Add to pipeline
  54526. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54527. };
  54528. // Create blur H&V post-processes
  54529. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  54530. var _this = this;
  54531. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  54532. var engine = scene.getEngine();
  54533. 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);
  54534. 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);
  54535. blurX.onActivateObservable.add(function () {
  54536. var dw = blurX.width / engine.getRenderingCanvas().width;
  54537. blurX.kernel = _this[blurWidthKey] * dw;
  54538. });
  54539. blurY.onActivateObservable.add(function () {
  54540. var dw = blurY.height / engine.getRenderingCanvas().height;
  54541. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  54542. });
  54543. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  54544. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  54545. this.blurHPostProcesses.push(blurX);
  54546. this.blurVPostProcesses.push(blurY);
  54547. };
  54548. // Create texture adder post-process
  54549. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54550. var _this = this;
  54551. 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);
  54552. this.textureAdderPostProcess.onApply = function (effect) {
  54553. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  54554. effect.setTexture("lensSampler", _this.lensTexture);
  54555. effect.setFloat("exposure", _this.exposure);
  54556. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  54557. };
  54558. // Add to pipeline
  54559. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54560. };
  54561. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  54562. var _this = this;
  54563. var geometryRenderer = scene.enableGeometryBufferRenderer();
  54564. geometryRenderer.enablePosition = true;
  54565. var geometry = geometryRenderer.getGBuffer();
  54566. // Base post-process
  54567. 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));
  54568. var depthValues = BABYLON.Vector2.Zero();
  54569. this.volumetricLightPostProcess.onApply = function (effect) {
  54570. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  54571. var generator = _this.sourceLight.getShadowGenerator();
  54572. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  54573. effect.setTexture("positionSampler", geometry.textures[2]);
  54574. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  54575. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  54576. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  54577. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  54578. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  54579. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  54580. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  54581. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  54582. effect.setVector2("depthValues", depthValues);
  54583. }
  54584. };
  54585. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  54586. // Smooth
  54587. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  54588. // Merge
  54589. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  54590. this.volumetricLightMergePostProces.onApply = function (effect) {
  54591. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  54592. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  54593. };
  54594. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  54595. };
  54596. // Create luminance
  54597. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  54598. var _this = this;
  54599. // Create luminance
  54600. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  54601. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  54602. var offsets = [];
  54603. this.luminancePostProcess.onApply = function (effect) {
  54604. var sU = (1.0 / _this.luminancePostProcess.width);
  54605. var sV = (1.0 / _this.luminancePostProcess.height);
  54606. offsets[0] = -0.5 * sU;
  54607. offsets[1] = 0.5 * sV;
  54608. offsets[2] = 0.5 * sU;
  54609. offsets[3] = 0.5 * sV;
  54610. offsets[4] = -0.5 * sU;
  54611. offsets[5] = -0.5 * sV;
  54612. offsets[6] = 0.5 * sU;
  54613. offsets[7] = -0.5 * sV;
  54614. effect.setArray2("lumOffsets", offsets);
  54615. };
  54616. // Add to pipeline
  54617. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  54618. // Create down sample luminance
  54619. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  54620. var size = Math.pow(3, i);
  54621. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  54622. if (i === 0) {
  54623. defines += "#define FINAL_DOWN_SAMPLER";
  54624. }
  54625. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  54626. this.luminanceDownSamplePostProcesses.push(postProcess);
  54627. }
  54628. // Create callbacks and add effects
  54629. var lastLuminance = this.luminancePostProcess;
  54630. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  54631. var downSampleOffsets = new Array(18);
  54632. pp.onApply = function (effect) {
  54633. var id = 0;
  54634. for (var x = -1; x < 2; x++) {
  54635. for (var y = -1; y < 2; y++) {
  54636. downSampleOffsets[id] = x / lastLuminance.width;
  54637. downSampleOffsets[id + 1] = y / lastLuminance.height;
  54638. id += 2;
  54639. }
  54640. }
  54641. effect.setArray2("dsOffsets", downSampleOffsets);
  54642. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  54643. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  54644. lastLuminance = _this.luminancePostProcess;
  54645. }
  54646. else {
  54647. lastLuminance = pp;
  54648. }
  54649. };
  54650. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  54651. pp.onAfterRender = function (effect) {
  54652. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54653. 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);
  54654. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54655. };
  54656. }
  54657. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  54658. });
  54659. };
  54660. // Create HDR post-process
  54661. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  54662. var _this = this;
  54663. 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);
  54664. var outputLiminance = 1;
  54665. var time = 0;
  54666. var lastTime = 0;
  54667. this.hdrPostProcess.onApply = function (effect) {
  54668. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  54669. time += scene.getEngine().getDeltaTime();
  54670. if (outputLiminance < 0) {
  54671. outputLiminance = _this._hdrCurrentLuminance;
  54672. }
  54673. else {
  54674. var dt = (lastTime - time) / 1000.0;
  54675. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  54676. outputLiminance += _this.hdrDecreaseRate * dt;
  54677. }
  54678. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  54679. outputLiminance -= _this.hdrIncreaseRate * dt;
  54680. }
  54681. else {
  54682. outputLiminance = _this._hdrCurrentLuminance;
  54683. }
  54684. }
  54685. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  54686. effect.setFloat("averageLuminance", outputLiminance);
  54687. lastTime = time;
  54688. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  54689. };
  54690. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  54691. };
  54692. // Create lens flare post-process
  54693. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54694. var _this = this;
  54695. 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);
  54696. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  54697. this._createBlurPostProcesses(scene, ratio / 4, 2);
  54698. 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);
  54699. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  54700. var resolution = new BABYLON.Vector2(0, 0);
  54701. // Lens flare
  54702. this.lensFlarePostProcess.onApply = function (effect) {
  54703. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  54704. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54705. effect.setFloat("strength", _this.lensFlareStrength);
  54706. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54707. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54708. // Shift
  54709. resolution.x = _this.lensFlarePostProcess.width;
  54710. resolution.y = _this.lensFlarePostProcess.height;
  54711. effect.setVector2("resolution", resolution);
  54712. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54713. };
  54714. // Compose
  54715. 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);
  54716. 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);
  54717. this.lensFlareComposePostProcess.onApply = function (effect) {
  54718. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  54719. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54720. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54721. // Lens start rotation matrix
  54722. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54723. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54724. 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));
  54725. camRot *= 4.0;
  54726. 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);
  54727. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54728. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54729. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  54730. };
  54731. };
  54732. // Create depth-of-field post-process
  54733. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54734. var _this = this;
  54735. 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);
  54736. this.depthOfFieldPostProcess.onApply = function (effect) {
  54737. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  54738. effect.setTexture("depthSampler", _this._getDepthTexture());
  54739. effect.setFloat("distance", _this.depthOfFieldDistance);
  54740. };
  54741. // Add to pipeline
  54742. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54743. };
  54744. // Create motion blur post-process
  54745. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  54746. var _this = this;
  54747. 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);
  54748. var motionScale = 0;
  54749. var prevViewProjection = BABYLON.Matrix.Identity();
  54750. var invViewProjection = BABYLON.Matrix.Identity();
  54751. var viewProjection = BABYLON.Matrix.Identity();
  54752. var screenSize = BABYLON.Vector2.Zero();
  54753. this.motionBlurPostProcess.onApply = function (effect) {
  54754. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  54755. viewProjection.invertToRef(invViewProjection);
  54756. effect.setMatrix("inverseViewProjection", invViewProjection);
  54757. effect.setMatrix("prevViewProjection", prevViewProjection);
  54758. prevViewProjection = viewProjection;
  54759. screenSize.x = _this.motionBlurPostProcess.width;
  54760. screenSize.y = _this.motionBlurPostProcess.height;
  54761. effect.setVector2("screenSize", screenSize);
  54762. motionScale = scene.getEngine().getFps() / 60.0;
  54763. effect.setFloat("motionScale", motionScale);
  54764. effect.setFloat("motionStrength", _this.motionStrength);
  54765. effect.setTexture("depthSampler", _this._getDepthTexture());
  54766. };
  54767. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  54768. };
  54769. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  54770. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  54771. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  54772. }
  54773. return this._scene.enableDepthRenderer().getDepthMap();
  54774. };
  54775. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  54776. for (var i = 0; i < this._cameras.length; i++) {
  54777. var camera = this._cameras[i];
  54778. if (this.originalPostProcess) {
  54779. this.originalPostProcess.dispose(camera);
  54780. }
  54781. if (this.downSampleX4PostProcess) {
  54782. this.downSampleX4PostProcess.dispose(camera);
  54783. }
  54784. if (this.brightPassPostProcess) {
  54785. this.brightPassPostProcess.dispose(camera);
  54786. }
  54787. if (this.textureAdderPostProcess) {
  54788. this.textureAdderPostProcess.dispose(camera);
  54789. }
  54790. if (this.textureAdderFinalPostProcess) {
  54791. this.textureAdderFinalPostProcess.dispose(camera);
  54792. }
  54793. if (this.volumetricLightPostProcess) {
  54794. this.volumetricLightPostProcess.dispose(camera);
  54795. }
  54796. if (this.volumetricLightSmoothXPostProcess) {
  54797. this.volumetricLightSmoothXPostProcess.dispose(camera);
  54798. }
  54799. if (this.volumetricLightSmoothYPostProcess) {
  54800. this.volumetricLightSmoothYPostProcess.dispose(camera);
  54801. }
  54802. if (this.volumetricLightMergePostProces) {
  54803. this.volumetricLightMergePostProces.dispose(camera);
  54804. }
  54805. if (this.volumetricLightFinalPostProcess) {
  54806. this.volumetricLightFinalPostProcess.dispose(camera);
  54807. }
  54808. if (this.lensFlarePostProcess) {
  54809. this.lensFlarePostProcess.dispose(camera);
  54810. }
  54811. if (this.lensFlareComposePostProcess) {
  54812. this.lensFlareComposePostProcess.dispose(camera);
  54813. }
  54814. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  54815. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  54816. }
  54817. if (this.luminancePostProcess) {
  54818. this.luminancePostProcess.dispose(camera);
  54819. }
  54820. if (this.hdrPostProcess) {
  54821. this.hdrPostProcess.dispose(camera);
  54822. }
  54823. if (this.hdrFinalPostProcess) {
  54824. this.hdrFinalPostProcess.dispose(camera);
  54825. }
  54826. if (this.depthOfFieldPostProcess) {
  54827. this.depthOfFieldPostProcess.dispose(camera);
  54828. }
  54829. if (this.motionBlurPostProcess) {
  54830. this.motionBlurPostProcess.dispose(camera);
  54831. }
  54832. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  54833. this.blurHPostProcesses[j].dispose(camera);
  54834. }
  54835. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  54836. this.blurVPostProcesses[j].dispose(camera);
  54837. }
  54838. }
  54839. this.originalPostProcess = null;
  54840. this.downSampleX4PostProcess = null;
  54841. this.brightPassPostProcess = null;
  54842. this.textureAdderPostProcess = null;
  54843. this.textureAdderFinalPostProcess = null;
  54844. this.volumetricLightPostProcess = null;
  54845. this.volumetricLightSmoothXPostProcess = null;
  54846. this.volumetricLightSmoothYPostProcess = null;
  54847. this.volumetricLightMergePostProces = null;
  54848. this.volumetricLightFinalPostProcess = null;
  54849. this.lensFlarePostProcess = null;
  54850. this.lensFlareComposePostProcess = null;
  54851. this.luminancePostProcess = null;
  54852. this.hdrPostProcess = null;
  54853. this.hdrFinalPostProcess = null;
  54854. this.depthOfFieldPostProcess = null;
  54855. this.motionBlurPostProcess = null;
  54856. this.luminanceDownSamplePostProcesses = [];
  54857. this.blurHPostProcesses = [];
  54858. this.blurVPostProcesses = [];
  54859. };
  54860. // Dispose
  54861. StandardRenderingPipeline.prototype.dispose = function () {
  54862. this._disposePostProcesses();
  54863. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  54864. _super.prototype.dispose.call(this);
  54865. };
  54866. // Serialize rendering pipeline
  54867. StandardRenderingPipeline.prototype.serialize = function () {
  54868. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54869. serializationObject.customType = "StandardRenderingPipeline";
  54870. return serializationObject;
  54871. };
  54872. /**
  54873. * Static members
  54874. */
  54875. // Parse serialized pipeline
  54876. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  54877. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  54878. };
  54879. // Luminance steps
  54880. StandardRenderingPipeline.LuminanceSteps = 6;
  54881. __decorate([
  54882. BABYLON.serialize()
  54883. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  54884. __decorate([
  54885. BABYLON.serialize()
  54886. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  54887. __decorate([
  54888. BABYLON.serialize()
  54889. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  54890. __decorate([
  54891. BABYLON.serialize()
  54892. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  54893. __decorate([
  54894. BABYLON.serializeAsTexture("lensTexture")
  54895. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  54896. __decorate([
  54897. BABYLON.serialize()
  54898. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  54899. __decorate([
  54900. BABYLON.serialize()
  54901. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  54902. __decorate([
  54903. BABYLON.serialize()
  54904. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  54905. __decorate([
  54906. BABYLON.serialize()
  54907. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  54908. __decorate([
  54909. BABYLON.serialize()
  54910. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  54911. __decorate([
  54912. BABYLON.serialize()
  54913. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  54914. __decorate([
  54915. BABYLON.serializeAsTexture("lensColorTexture")
  54916. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  54917. __decorate([
  54918. BABYLON.serialize()
  54919. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  54920. __decorate([
  54921. BABYLON.serialize()
  54922. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  54923. __decorate([
  54924. BABYLON.serialize()
  54925. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  54926. __decorate([
  54927. BABYLON.serialize()
  54928. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  54929. __decorate([
  54930. BABYLON.serializeAsTexture("lensStarTexture")
  54931. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  54932. __decorate([
  54933. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  54934. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  54935. __decorate([
  54936. BABYLON.serialize()
  54937. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  54938. __decorate([
  54939. BABYLON.serialize()
  54940. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  54941. __decorate([
  54942. BABYLON.serialize()
  54943. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  54944. __decorate([
  54945. BABYLON.serialize()
  54946. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  54947. __decorate([
  54948. BABYLON.serialize()
  54949. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  54950. __decorate([
  54951. BABYLON.serialize()
  54952. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  54953. __decorate([
  54954. BABYLON.serialize()
  54955. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  54956. __decorate([
  54957. BABYLON.serialize()
  54958. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  54959. __decorate([
  54960. BABYLON.serialize()
  54961. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  54962. __decorate([
  54963. BABYLON.serialize()
  54964. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  54965. __decorate([
  54966. BABYLON.serialize()
  54967. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  54968. return StandardRenderingPipeline;
  54969. }(BABYLON.PostProcessRenderPipeline));
  54970. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54971. })(BABYLON || (BABYLON = {}));
  54972. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54973. var BABYLON;
  54974. (function (BABYLON) {
  54975. var FxaaPostProcess = (function (_super) {
  54976. __extends(FxaaPostProcess, _super);
  54977. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54978. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54979. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  54980. _this.onApplyObservable.add(function (effect) {
  54981. var texelSize = _this.texelSize;
  54982. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  54983. });
  54984. return _this;
  54985. }
  54986. return FxaaPostProcess;
  54987. }(BABYLON.PostProcess));
  54988. BABYLON.FxaaPostProcess = FxaaPostProcess;
  54989. })(BABYLON || (BABYLON = {}));
  54990. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  54991. var BABYLON;
  54992. (function (BABYLON) {
  54993. var DefaultRenderingPipeline = (function (_super) {
  54994. __extends(DefaultRenderingPipeline, _super);
  54995. /**
  54996. * @constructor
  54997. * @param {string} name - The rendering pipeline name
  54998. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54999. * @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)
  55000. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55001. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  55002. */
  55003. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  55004. if (automaticBuild === void 0) { automaticBuild = true; }
  55005. var _this = _super.call(this, scene.getEngine(), name) || this;
  55006. _this.PassPostProcessId = "PassPostProcessEffect";
  55007. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  55008. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  55009. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  55010. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  55011. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  55012. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  55013. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  55014. // IAnimatable
  55015. _this.animations = [];
  55016. // Values
  55017. _this._bloomEnabled = false;
  55018. _this._fxaaEnabled = false;
  55019. _this._imageProcessingEnabled = true;
  55020. _this._bloomScale = 0.6;
  55021. _this._buildAllowed = true;
  55022. /**
  55023. * Specifies the size of the bloom blur kernel, relative to the final output size
  55024. */
  55025. _this.bloomKernel = 64;
  55026. /**
  55027. * Specifies the weight of the bloom in the final rendering
  55028. */
  55029. _this._bloomWeight = 0.15;
  55030. _this._cameras = cameras || [];
  55031. _this._buildAllowed = automaticBuild;
  55032. // Initialize
  55033. _this._scene = scene;
  55034. var caps = _this._scene.getEngine().getCaps();
  55035. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  55036. // Misc
  55037. if (_this._hdr) {
  55038. if (caps.textureHalfFloatRender) {
  55039. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55040. }
  55041. else if (caps.textureFloatRender) {
  55042. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55043. }
  55044. }
  55045. else {
  55046. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55047. }
  55048. // Attach
  55049. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55050. _this._buildPipeline();
  55051. return _this;
  55052. }
  55053. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  55054. get: function () {
  55055. return this._bloomWeight;
  55056. },
  55057. set: function (value) {
  55058. if (this._bloomWeight === value) {
  55059. return;
  55060. }
  55061. this._bloomWeight = value;
  55062. if (this._hdr && this.copyBack) {
  55063. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  55064. }
  55065. },
  55066. enumerable: true,
  55067. configurable: true
  55068. });
  55069. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  55070. get: function () {
  55071. return this._bloomScale;
  55072. },
  55073. set: function (value) {
  55074. if (this._bloomScale === value) {
  55075. return;
  55076. }
  55077. this._bloomScale = value;
  55078. this._buildPipeline();
  55079. },
  55080. enumerable: true,
  55081. configurable: true
  55082. });
  55083. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  55084. get: function () {
  55085. return this._bloomEnabled;
  55086. },
  55087. set: function (enabled) {
  55088. if (this._bloomEnabled === enabled) {
  55089. return;
  55090. }
  55091. this._bloomEnabled = enabled;
  55092. this._buildPipeline();
  55093. },
  55094. enumerable: true,
  55095. configurable: true
  55096. });
  55097. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  55098. get: function () {
  55099. return this._fxaaEnabled;
  55100. },
  55101. set: function (enabled) {
  55102. if (this._fxaaEnabled === enabled) {
  55103. return;
  55104. }
  55105. this._fxaaEnabled = enabled;
  55106. this._buildPipeline();
  55107. },
  55108. enumerable: true,
  55109. configurable: true
  55110. });
  55111. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  55112. get: function () {
  55113. return this._imageProcessingEnabled;
  55114. },
  55115. set: function (enabled) {
  55116. if (this._imageProcessingEnabled === enabled) {
  55117. return;
  55118. }
  55119. this._imageProcessingEnabled = enabled;
  55120. this._buildPipeline();
  55121. },
  55122. enumerable: true,
  55123. configurable: true
  55124. });
  55125. /**
  55126. * Force the compilation of the entire pipeline.
  55127. */
  55128. DefaultRenderingPipeline.prototype.prepare = function () {
  55129. var previousState = this._buildAllowed;
  55130. this._buildAllowed = true;
  55131. this._buildPipeline();
  55132. this._buildAllowed = previousState;
  55133. };
  55134. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  55135. var _this = this;
  55136. if (!this._buildAllowed) {
  55137. return;
  55138. }
  55139. var engine = this._scene.getEngine();
  55140. this._disposePostProcesses();
  55141. this._reset();
  55142. if (this.bloomEnabled) {
  55143. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55144. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  55145. if (!this._hdr) {
  55146. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55147. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  55148. this.highlights.autoClear = false;
  55149. this.highlights.alwaysForcePOT = true;
  55150. }
  55151. 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);
  55152. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  55153. this.blurX.alwaysForcePOT = true;
  55154. this.blurX.autoClear = false;
  55155. this.blurX.onActivateObservable.add(function () {
  55156. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  55157. _this.blurX.kernel = _this.bloomKernel * dw;
  55158. });
  55159. 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);
  55160. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  55161. this.blurY.alwaysForcePOT = true;
  55162. this.blurY.autoClear = false;
  55163. this.blurY.onActivateObservable.add(function () {
  55164. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  55165. _this.blurY.kernel = _this.bloomKernel * dh;
  55166. });
  55167. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55168. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  55169. this.copyBack.alwaysForcePOT = true;
  55170. if (this._hdr) {
  55171. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  55172. var w = this.bloomWeight;
  55173. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  55174. }
  55175. else {
  55176. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  55177. }
  55178. this.copyBack.autoClear = false;
  55179. }
  55180. if (this._imageProcessingEnabled) {
  55181. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55182. if (this._hdr) {
  55183. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  55184. }
  55185. else {
  55186. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  55187. }
  55188. }
  55189. if (this.fxaaEnabled) {
  55190. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55191. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  55192. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  55193. }
  55194. else {
  55195. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55196. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  55197. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  55198. }
  55199. if (this.bloomEnabled) {
  55200. if (this._hdr) {
  55201. this.copyBack.shareOutputWith(this.blurX);
  55202. if (this.imageProcessing) {
  55203. this.imageProcessing.shareOutputWith(this.pass);
  55204. this.imageProcessing.autoClear = false;
  55205. }
  55206. else if (this.fxaa) {
  55207. this.fxaa.shareOutputWith(this.pass);
  55208. }
  55209. else {
  55210. this.finalMerge.shareOutputWith(this.pass);
  55211. }
  55212. }
  55213. else {
  55214. if (this.fxaa) {
  55215. this.fxaa.shareOutputWith(this.pass);
  55216. }
  55217. else {
  55218. this.finalMerge.shareOutputWith(this.pass);
  55219. }
  55220. }
  55221. }
  55222. if (this._cameras !== null) {
  55223. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  55224. }
  55225. };
  55226. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  55227. for (var i = 0; i < this._cameras.length; i++) {
  55228. var camera = this._cameras[i];
  55229. if (this.pass) {
  55230. this.pass.dispose(camera);
  55231. }
  55232. if (this.highlights) {
  55233. this.highlights.dispose(camera);
  55234. }
  55235. if (this.blurX) {
  55236. this.blurX.dispose(camera);
  55237. }
  55238. if (this.blurY) {
  55239. this.blurY.dispose(camera);
  55240. }
  55241. if (this.copyBack) {
  55242. this.copyBack.dispose(camera);
  55243. }
  55244. if (this.imageProcessing) {
  55245. this.imageProcessing.dispose(camera);
  55246. }
  55247. if (this.fxaa) {
  55248. this.fxaa.dispose(camera);
  55249. }
  55250. if (this.finalMerge) {
  55251. this.finalMerge.dispose(camera);
  55252. }
  55253. }
  55254. this.pass = null;
  55255. this.highlights = null;
  55256. this.blurX = null;
  55257. this.blurY = null;
  55258. this.copyBack = null;
  55259. this.imageProcessing = null;
  55260. this.fxaa = null;
  55261. this.finalMerge = null;
  55262. };
  55263. // Dispose
  55264. DefaultRenderingPipeline.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. DefaultRenderingPipeline.prototype.serialize = function () {
  55271. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55272. serializationObject.customType = "DefaultRenderingPipeline";
  55273. return serializationObject;
  55274. };
  55275. // Parse serialized pipeline
  55276. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  55277. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  55278. };
  55279. __decorate([
  55280. BABYLON.serialize()
  55281. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  55282. __decorate([
  55283. BABYLON.serialize()
  55284. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  55285. __decorate([
  55286. BABYLON.serialize()
  55287. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  55288. __decorate([
  55289. BABYLON.serialize()
  55290. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  55291. __decorate([
  55292. BABYLON.serialize()
  55293. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  55294. __decorate([
  55295. BABYLON.serialize()
  55296. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  55297. __decorate([
  55298. BABYLON.serialize()
  55299. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  55300. __decorate([
  55301. BABYLON.serialize()
  55302. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  55303. return DefaultRenderingPipeline;
  55304. }(BABYLON.PostProcessRenderPipeline));
  55305. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  55306. })(BABYLON || (BABYLON = {}));
  55307. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  55308. var BABYLON;
  55309. (function (BABYLON) {
  55310. var GeometryBufferRenderer = (function () {
  55311. function GeometryBufferRenderer(scene, ratio) {
  55312. if (ratio === void 0) { ratio = 1; }
  55313. this._viewMatrix = BABYLON.Matrix.Zero();
  55314. this._projectionMatrix = BABYLON.Matrix.Zero();
  55315. this._transformMatrix = BABYLON.Matrix.Zero();
  55316. this._worldViewProjection = BABYLON.Matrix.Zero();
  55317. this._enablePosition = false;
  55318. this._scene = scene;
  55319. this._ratio = ratio;
  55320. // Render target
  55321. this._createRenderTargets();
  55322. }
  55323. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  55324. set: function (meshes) {
  55325. this._multiRenderTarget.renderList = meshes;
  55326. },
  55327. enumerable: true,
  55328. configurable: true
  55329. });
  55330. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  55331. get: function () {
  55332. return this._multiRenderTarget.isSupported;
  55333. },
  55334. enumerable: true,
  55335. configurable: true
  55336. });
  55337. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  55338. get: function () {
  55339. return this._enablePosition;
  55340. },
  55341. set: function (enable) {
  55342. this._enablePosition = enable;
  55343. this.dispose();
  55344. this._createRenderTargets();
  55345. },
  55346. enumerable: true,
  55347. configurable: true
  55348. });
  55349. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  55350. var material = subMesh.getMaterial();
  55351. if (material && material.disableDepthWrite) {
  55352. return false;
  55353. }
  55354. var defines = [];
  55355. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  55356. var mesh = subMesh.getMesh();
  55357. var scene = mesh.getScene();
  55358. // Alpha test
  55359. if (material && material.needAlphaTesting()) {
  55360. defines.push("#define ALPHATEST");
  55361. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55362. attribs.push(BABYLON.VertexBuffer.UVKind);
  55363. defines.push("#define UV1");
  55364. }
  55365. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55366. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55367. defines.push("#define UV2");
  55368. }
  55369. }
  55370. // Buffers
  55371. if (this._enablePosition) {
  55372. defines.push("#define POSITION");
  55373. }
  55374. // Bones
  55375. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55376. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55377. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55378. if (mesh.numBoneInfluencers > 4) {
  55379. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55380. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55381. }
  55382. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55383. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55384. }
  55385. else {
  55386. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55387. }
  55388. // Instances
  55389. if (useInstances) {
  55390. defines.push("#define INSTANCES");
  55391. attribs.push("world0");
  55392. attribs.push("world1");
  55393. attribs.push("world2");
  55394. attribs.push("world3");
  55395. }
  55396. // Get correct effect
  55397. var join = defines.join("\n");
  55398. if (this._cachedDefines !== join) {
  55399. this._cachedDefines = join;
  55400. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  55401. }
  55402. return this._effect.isReady();
  55403. };
  55404. GeometryBufferRenderer.prototype.getGBuffer = function () {
  55405. return this._multiRenderTarget;
  55406. };
  55407. // Methods
  55408. GeometryBufferRenderer.prototype.dispose = function () {
  55409. this.getGBuffer().dispose();
  55410. };
  55411. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  55412. var _this = this;
  55413. var engine = this._scene.getEngine();
  55414. var count = this._enablePosition ? 3 : 2;
  55415. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  55416. if (!this.isSupported) {
  55417. return null;
  55418. }
  55419. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55420. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55421. this._multiRenderTarget.refreshRate = 1;
  55422. this._multiRenderTarget.renderParticles = false;
  55423. this._multiRenderTarget.renderList = null;
  55424. // set default depth value to 1.0 (far away)
  55425. this._multiRenderTarget.onClearObservable.add(function (engine) {
  55426. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  55427. });
  55428. // Custom render function
  55429. var renderSubMesh = function (subMesh) {
  55430. var mesh = subMesh.getRenderingMesh();
  55431. var scene = _this._scene;
  55432. var engine = scene.getEngine();
  55433. // Culling
  55434. engine.setState(subMesh.getMaterial().backFaceCulling);
  55435. // Managing instances
  55436. var batch = mesh._getInstancesRenderList(subMesh._id);
  55437. if (batch.mustReturn) {
  55438. return;
  55439. }
  55440. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55441. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55442. engine.enableEffect(_this._effect);
  55443. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55444. var material = subMesh.getMaterial();
  55445. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55446. _this._effect.setMatrix("view", scene.getViewMatrix());
  55447. // Alpha test
  55448. if (material && material.needAlphaTesting()) {
  55449. var alphaTexture = material.getAlphaTestTexture();
  55450. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55451. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55452. }
  55453. // Bones
  55454. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55455. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55456. }
  55457. // Draw
  55458. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55459. }
  55460. };
  55461. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55462. var index;
  55463. if (depthOnlySubMeshes.length) {
  55464. engine.setColorWrite(false);
  55465. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55466. renderSubMesh(depthOnlySubMeshes.data[index]);
  55467. }
  55468. engine.setColorWrite(true);
  55469. }
  55470. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55471. renderSubMesh(opaqueSubMeshes.data[index]);
  55472. }
  55473. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55474. renderSubMesh(alphaTestSubMeshes.data[index]);
  55475. }
  55476. };
  55477. };
  55478. return GeometryBufferRenderer;
  55479. }());
  55480. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  55481. })(BABYLON || (BABYLON = {}));
  55482. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  55483. var BABYLON;
  55484. (function (BABYLON) {
  55485. var RefractionPostProcess = (function (_super) {
  55486. __extends(RefractionPostProcess, _super);
  55487. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  55488. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  55489. _this.color = color;
  55490. _this.depth = depth;
  55491. _this.colorLevel = colorLevel;
  55492. _this.onActivateObservable.add(function (cam) {
  55493. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  55494. });
  55495. _this.onApplyObservable.add(function (effect) {
  55496. effect.setColor3("baseColor", _this.color);
  55497. effect.setFloat("depth", _this.depth);
  55498. effect.setFloat("colorLevel", _this.colorLevel);
  55499. effect.setTexture("refractionSampler", _this._refRexture);
  55500. });
  55501. return _this;
  55502. }
  55503. // Methods
  55504. RefractionPostProcess.prototype.dispose = function (camera) {
  55505. if (this._refRexture) {
  55506. this._refRexture.dispose();
  55507. }
  55508. _super.prototype.dispose.call(this, camera);
  55509. };
  55510. return RefractionPostProcess;
  55511. }(BABYLON.PostProcess));
  55512. BABYLON.RefractionPostProcess = RefractionPostProcess;
  55513. })(BABYLON || (BABYLON = {}));
  55514. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  55515. var BABYLON;
  55516. (function (BABYLON) {
  55517. var BlackAndWhitePostProcess = (function (_super) {
  55518. __extends(BlackAndWhitePostProcess, _super);
  55519. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  55520. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  55521. _this.degree = 1;
  55522. _this.onApplyObservable.add(function (effect) {
  55523. effect.setFloat("degree", _this.degree);
  55524. });
  55525. return _this;
  55526. }
  55527. return BlackAndWhitePostProcess;
  55528. }(BABYLON.PostProcess));
  55529. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  55530. })(BABYLON || (BABYLON = {}));
  55531. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  55532. var BABYLON;
  55533. (function (BABYLON) {
  55534. var ConvolutionPostProcess = (function (_super) {
  55535. __extends(ConvolutionPostProcess, _super);
  55536. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  55537. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  55538. _this.kernel = kernel;
  55539. _this.onApply = function (effect) {
  55540. effect.setFloat2("screenSize", _this.width, _this.height);
  55541. effect.setArray("kernel", _this.kernel);
  55542. };
  55543. return _this;
  55544. }
  55545. // Statics
  55546. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  55547. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  55548. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  55549. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  55550. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  55551. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  55552. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  55553. return ConvolutionPostProcess;
  55554. }(BABYLON.PostProcess));
  55555. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  55556. })(BABYLON || (BABYLON = {}));
  55557. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  55558. var BABYLON;
  55559. (function (BABYLON) {
  55560. var FilterPostProcess = (function (_super) {
  55561. __extends(FilterPostProcess, _super);
  55562. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  55563. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  55564. _this.kernelMatrix = kernelMatrix;
  55565. _this.onApply = function (effect) {
  55566. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  55567. };
  55568. return _this;
  55569. }
  55570. return FilterPostProcess;
  55571. }(BABYLON.PostProcess));
  55572. BABYLON.FilterPostProcess = FilterPostProcess;
  55573. })(BABYLON || (BABYLON = {}));
  55574. //# sourceMappingURL=babylon.filterPostProcess.js.map
  55575. var BABYLON;
  55576. (function (BABYLON) {
  55577. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  55578. var VolumetricLightScatteringPostProcess = (function (_super) {
  55579. __extends(VolumetricLightScatteringPostProcess, _super);
  55580. /**
  55581. * @constructor
  55582. * @param {string} name - The post-process name
  55583. * @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)
  55584. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  55585. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  55586. * @param {number} samples - The post-process quality, default 100
  55587. * @param {number} samplingMode - The post-process filtering mode
  55588. * @param {BABYLON.Engine} engine - The babylon engine
  55589. * @param {boolean} reusable - If the post-process is reusable
  55590. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55591. */
  55592. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55593. if (samples === void 0) { samples = 100; }
  55594. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55595. 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;
  55596. _this._screenCoordinates = BABYLON.Vector2.Zero();
  55597. /**
  55598. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55599. * @type {Vector3}
  55600. */
  55601. _this.customMeshPosition = BABYLON.Vector3.Zero();
  55602. /**
  55603. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55604. * @type {boolean}
  55605. */
  55606. _this.useCustomMeshPosition = false;
  55607. /**
  55608. * If the post-process should inverse the light scattering direction
  55609. * @type {boolean}
  55610. */
  55611. _this.invert = true;
  55612. /**
  55613. * Array containing the excluded meshes not rendered in the internal pass
  55614. */
  55615. _this.excludedMeshes = new Array();
  55616. /**
  55617. * Controls the overall intensity of the post-process
  55618. * @type {number}
  55619. */
  55620. _this.exposure = 0.3;
  55621. /**
  55622. * Dissipates each sample's contribution in range [0, 1]
  55623. * @type {number}
  55624. */
  55625. _this.decay = 0.96815;
  55626. /**
  55627. * Controls the overall intensity of each sample
  55628. * @type {number}
  55629. */
  55630. _this.weight = 0.58767;
  55631. /**
  55632. * Controls the density of each sample
  55633. * @type {number}
  55634. */
  55635. _this.density = 0.926;
  55636. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55637. var engine = scene.getEngine();
  55638. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55639. // Configure mesh
  55640. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55641. // Configure
  55642. _this._createPass(scene, ratio.passRatio || ratio);
  55643. _this.onActivate = function (camera) {
  55644. if (!_this.isSupported) {
  55645. _this.dispose(camera);
  55646. }
  55647. _this.onActivate = null;
  55648. };
  55649. _this.onApplyObservable.add(function (effect) {
  55650. _this._updateMeshScreenCoordinates(scene);
  55651. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55652. effect.setFloat("exposure", _this.exposure);
  55653. effect.setFloat("decay", _this.decay);
  55654. effect.setFloat("weight", _this.weight);
  55655. effect.setFloat("density", _this.density);
  55656. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55657. });
  55658. return _this;
  55659. }
  55660. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55661. get: function () {
  55662. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55663. return false;
  55664. },
  55665. set: function (useDiffuseColor) {
  55666. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55667. },
  55668. enumerable: true,
  55669. configurable: true
  55670. });
  55671. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  55672. return "VolumetricLightScatteringPostProcess";
  55673. };
  55674. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  55675. var mesh = subMesh.getMesh();
  55676. // Render this.mesh as default
  55677. if (mesh === this.mesh) {
  55678. return mesh.material.isReady(mesh);
  55679. }
  55680. var defines = [];
  55681. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55682. var material = subMesh.getMaterial();
  55683. var needUV = false;
  55684. // Alpha test
  55685. if (material) {
  55686. if (material.needAlphaTesting()) {
  55687. defines.push("#define ALPHATEST");
  55688. }
  55689. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55690. attribs.push(BABYLON.VertexBuffer.UVKind);
  55691. defines.push("#define UV1");
  55692. }
  55693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55694. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55695. defines.push("#define UV2");
  55696. }
  55697. }
  55698. // Bones
  55699. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55700. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55701. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55702. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55703. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55704. }
  55705. else {
  55706. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55707. }
  55708. // Instances
  55709. if (useInstances) {
  55710. defines.push("#define INSTANCES");
  55711. attribs.push("world0");
  55712. attribs.push("world1");
  55713. attribs.push("world2");
  55714. attribs.push("world3");
  55715. }
  55716. // Get correct effect
  55717. var join = defines.join("\n");
  55718. if (this._cachedDefines !== join) {
  55719. this._cachedDefines = join;
  55720. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  55721. }
  55722. return this._volumetricLightScatteringPass.isReady();
  55723. };
  55724. /**
  55725. * Sets the new light position for light scattering effect
  55726. * @param {BABYLON.Vector3} The new custom light position
  55727. */
  55728. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  55729. this.customMeshPosition = position;
  55730. };
  55731. /**
  55732. * Returns the light position for light scattering effect
  55733. * @return {BABYLON.Vector3} The custom light position
  55734. */
  55735. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55736. return this.customMeshPosition;
  55737. };
  55738. /**
  55739. * Disposes the internal assets and detaches the post-process from the camera
  55740. */
  55741. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  55742. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  55743. if (rttIndex !== -1) {
  55744. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  55745. }
  55746. this._volumetricLightScatteringRTT.dispose();
  55747. _super.prototype.dispose.call(this, camera);
  55748. };
  55749. /**
  55750. * Returns the render target texture used by the post-process
  55751. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  55752. */
  55753. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  55754. return this._volumetricLightScatteringRTT;
  55755. };
  55756. // Private methods
  55757. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  55758. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  55759. return true;
  55760. }
  55761. return false;
  55762. };
  55763. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  55764. var _this = this;
  55765. var engine = scene.getEngine();
  55766. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55767. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55768. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55769. this._volumetricLightScatteringRTT.renderList = null;
  55770. this._volumetricLightScatteringRTT.renderParticles = false;
  55771. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  55772. // Custom render function for submeshes
  55773. var renderSubMesh = function (subMesh) {
  55774. var mesh = subMesh.getRenderingMesh();
  55775. if (_this._meshExcluded(mesh)) {
  55776. return;
  55777. }
  55778. var scene = mesh.getScene();
  55779. var engine = scene.getEngine();
  55780. // Culling
  55781. engine.setState(subMesh.getMaterial().backFaceCulling);
  55782. // Managing instances
  55783. var batch = mesh._getInstancesRenderList(subMesh._id);
  55784. if (batch.mustReturn) {
  55785. return;
  55786. }
  55787. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55788. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55789. var effect = _this._volumetricLightScatteringPass;
  55790. if (mesh === _this.mesh) {
  55791. if (subMesh.effect) {
  55792. effect = subMesh.effect;
  55793. }
  55794. else {
  55795. effect = subMesh.getMaterial().getEffect();
  55796. }
  55797. }
  55798. engine.enableEffect(effect);
  55799. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  55800. if (mesh === _this.mesh) {
  55801. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  55802. }
  55803. else {
  55804. var material = subMesh.getMaterial();
  55805. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  55806. // Alpha test
  55807. if (material && material.needAlphaTesting()) {
  55808. var alphaTexture = material.getAlphaTestTexture();
  55809. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  55810. if (alphaTexture) {
  55811. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55812. }
  55813. }
  55814. // Bones
  55815. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55816. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55817. }
  55818. }
  55819. // Draw
  55820. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  55821. }
  55822. };
  55823. // Render target texture callbacks
  55824. var savedSceneClearColor;
  55825. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  55826. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  55827. savedSceneClearColor = scene.clearColor;
  55828. scene.clearColor = sceneClearColor;
  55829. });
  55830. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  55831. scene.clearColor = savedSceneClearColor;
  55832. });
  55833. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55834. var engine = scene.getEngine();
  55835. var index;
  55836. if (depthOnlySubMeshes.length) {
  55837. engine.setColorWrite(false);
  55838. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55839. renderSubMesh(depthOnlySubMeshes.data[index]);
  55840. }
  55841. engine.setColorWrite(true);
  55842. }
  55843. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55844. renderSubMesh(opaqueSubMeshes.data[index]);
  55845. }
  55846. engine.setAlphaTesting(true);
  55847. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55848. renderSubMesh(alphaTestSubMeshes.data[index]);
  55849. }
  55850. engine.setAlphaTesting(false);
  55851. if (transparentSubMeshes.length) {
  55852. // Sort sub meshes
  55853. for (index = 0; index < transparentSubMeshes.length; index++) {
  55854. var submesh = transparentSubMeshes.data[index];
  55855. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  55856. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  55857. }
  55858. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  55859. sortedArray.sort(function (a, b) {
  55860. // Alpha index first
  55861. if (a._alphaIndex > b._alphaIndex) {
  55862. return 1;
  55863. }
  55864. if (a._alphaIndex < b._alphaIndex) {
  55865. return -1;
  55866. }
  55867. // Then distance to camera
  55868. if (a._distanceToCamera < b._distanceToCamera) {
  55869. return 1;
  55870. }
  55871. if (a._distanceToCamera > b._distanceToCamera) {
  55872. return -1;
  55873. }
  55874. return 0;
  55875. });
  55876. // Render sub meshes
  55877. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55878. for (index = 0; index < sortedArray.length; index++) {
  55879. renderSubMesh(sortedArray[index]);
  55880. }
  55881. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55882. }
  55883. };
  55884. };
  55885. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  55886. var transform = scene.getTransformMatrix();
  55887. var meshPosition;
  55888. if (this.useCustomMeshPosition) {
  55889. meshPosition = this.customMeshPosition;
  55890. }
  55891. else if (this.attachedNode) {
  55892. meshPosition = this.attachedNode.position;
  55893. }
  55894. else {
  55895. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  55896. }
  55897. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  55898. this._screenCoordinates.x = pos.x / this._viewPort.width;
  55899. this._screenCoordinates.y = pos.y / this._viewPort.height;
  55900. if (this.invert)
  55901. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  55902. };
  55903. // Static methods
  55904. /**
  55905. * Creates a default mesh for the Volumeric Light Scattering post-process
  55906. * @param {string} The mesh name
  55907. * @param {BABYLON.Scene} The scene where to create the mesh
  55908. * @return {BABYLON.Mesh} the default mesh
  55909. */
  55910. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  55911. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  55912. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55913. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  55914. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  55915. mesh.material = material;
  55916. return mesh;
  55917. };
  55918. __decorate([
  55919. BABYLON.serializeAsVector3()
  55920. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  55921. __decorate([
  55922. BABYLON.serialize()
  55923. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  55924. __decorate([
  55925. BABYLON.serialize()
  55926. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  55927. __decorate([
  55928. BABYLON.serializeAsMeshReference()
  55929. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  55930. __decorate([
  55931. BABYLON.serialize()
  55932. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  55933. __decorate([
  55934. BABYLON.serialize()
  55935. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  55936. __decorate([
  55937. BABYLON.serialize()
  55938. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  55939. __decorate([
  55940. BABYLON.serialize()
  55941. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  55942. __decorate([
  55943. BABYLON.serialize()
  55944. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  55945. return VolumetricLightScatteringPostProcess;
  55946. }(BABYLON.PostProcess));
  55947. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  55948. })(BABYLON || (BABYLON = {}));
  55949. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  55950. //
  55951. // This post-process allows the modification of rendered colors by using
  55952. // a 'look-up table' (LUT). This effect is also called Color Grading.
  55953. //
  55954. // The object needs to be provided an url to a texture containing the color
  55955. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  55956. // Use an image editing software to tweak the LUT to match your needs.
  55957. //
  55958. // For an example of a color LUT, see here:
  55959. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  55960. // For explanations on color grading, see here:
  55961. // http://udn.epicgames.com/Three/ColorGrading.html
  55962. //
  55963. var BABYLON;
  55964. (function (BABYLON) {
  55965. var ColorCorrectionPostProcess = (function (_super) {
  55966. __extends(ColorCorrectionPostProcess, _super);
  55967. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  55968. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  55969. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55970. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  55971. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55972. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55973. _this.onApply = function (effect) {
  55974. effect.setTexture("colorTable", _this._colorTableTexture);
  55975. };
  55976. return _this;
  55977. }
  55978. return ColorCorrectionPostProcess;
  55979. }(BABYLON.PostProcess));
  55980. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  55981. })(BABYLON || (BABYLON = {}));
  55982. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  55983. var BABYLON;
  55984. (function (BABYLON) {
  55985. var TonemappingOperator;
  55986. (function (TonemappingOperator) {
  55987. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  55988. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  55989. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  55990. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  55991. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  55992. ;
  55993. var TonemapPostProcess = (function (_super) {
  55994. __extends(TonemapPostProcess, _super);
  55995. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  55996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55997. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55998. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  55999. _this._operator = _operator;
  56000. _this.exposureAdjustment = exposureAdjustment;
  56001. var defines = "#define ";
  56002. if (_this._operator === TonemappingOperator.Hable)
  56003. defines += "HABLE_TONEMAPPING";
  56004. else if (_this._operator === TonemappingOperator.Reinhard)
  56005. defines += "REINHARD_TONEMAPPING";
  56006. else if (_this._operator === TonemappingOperator.HejiDawson)
  56007. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  56008. else if (_this._operator === TonemappingOperator.Photographic)
  56009. defines += "PHOTOGRAPHIC_TONEMAPPING";
  56010. //sadly a second call to create the effect.
  56011. _this.updateEffect(defines);
  56012. _this.onApply = function (effect) {
  56013. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  56014. };
  56015. return _this;
  56016. }
  56017. return TonemapPostProcess;
  56018. }(BABYLON.PostProcess));
  56019. BABYLON.TonemapPostProcess = TonemapPostProcess;
  56020. })(BABYLON || (BABYLON = {}));
  56021. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  56022. var BABYLON;
  56023. (function (BABYLON) {
  56024. var DisplayPassPostProcess = (function (_super) {
  56025. __extends(DisplayPassPostProcess, _super);
  56026. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  56027. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  56028. }
  56029. return DisplayPassPostProcess;
  56030. }(BABYLON.PostProcess));
  56031. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  56032. })(BABYLON || (BABYLON = {}));
  56033. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  56034. var BABYLON;
  56035. (function (BABYLON) {
  56036. var HighlightsPostProcess = (function (_super) {
  56037. __extends(HighlightsPostProcess, _super);
  56038. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56039. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56040. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  56041. }
  56042. return HighlightsPostProcess;
  56043. }(BABYLON.PostProcess));
  56044. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  56045. })(BABYLON || (BABYLON = {}));
  56046. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  56047. var BABYLON;
  56048. (function (BABYLON) {
  56049. var ImageProcessingPostProcess = (function (_super) {
  56050. __extends(ImageProcessingPostProcess, _super);
  56051. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56052. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56053. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  56054. _this._fromLinearSpace = true;
  56055. /**
  56056. * Defines cache preventing GC.
  56057. */
  56058. _this._defines = {
  56059. IMAGEPROCESSING: false,
  56060. VIGNETTE: false,
  56061. VIGNETTEBLENDMODEMULTIPLY: false,
  56062. VIGNETTEBLENDMODEOPAQUE: false,
  56063. TONEMAPPING: false,
  56064. CONTRAST: false,
  56065. COLORCURVES: false,
  56066. COLORGRADING: false,
  56067. FROMLINEARSPACE: false,
  56068. SAMPLER3DGREENDEPTH: false,
  56069. SAMPLER3DBGRMAP: false,
  56070. IMAGEPROCESSINGPOSTPROCESS: false,
  56071. EXPOSURE: false,
  56072. };
  56073. // Setup the default processing configuration to the scene.
  56074. _this._attachImageProcessingConfiguration(null, true);
  56075. _this.imageProcessingConfiguration.applyByPostProcess = true;
  56076. _this.onApply = function (effect) {
  56077. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  56078. };
  56079. return _this;
  56080. }
  56081. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  56082. /**
  56083. * Gets the image processing configuration used either in this material.
  56084. */
  56085. get: function () {
  56086. return this._imageProcessingConfiguration;
  56087. },
  56088. /**
  56089. * Sets the Default image processing configuration used either in the this material.
  56090. *
  56091. * If sets to null, the scene one is in use.
  56092. */
  56093. set: function (value) {
  56094. this._attachImageProcessingConfiguration(value);
  56095. },
  56096. enumerable: true,
  56097. configurable: true
  56098. });
  56099. /**
  56100. * Attaches a new image processing configuration to the PBR Material.
  56101. * @param configuration
  56102. */
  56103. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  56104. var _this = this;
  56105. if (doNotBuild === void 0) { doNotBuild = false; }
  56106. if (configuration === this._imageProcessingConfiguration) {
  56107. return;
  56108. }
  56109. // Detaches observer.
  56110. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  56111. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  56112. }
  56113. // Pick the scene configuration if needed.
  56114. if (!configuration) {
  56115. var camera = this.getCamera();
  56116. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  56117. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  56118. }
  56119. else {
  56120. this._imageProcessingConfiguration = configuration;
  56121. }
  56122. // Attaches observer.
  56123. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  56124. _this._updateParameters();
  56125. });
  56126. // Ensure the effect will be rebuilt.
  56127. if (!doNotBuild) {
  56128. this._updateParameters();
  56129. }
  56130. };
  56131. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  56132. /**
  56133. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  56134. */
  56135. get: function () {
  56136. return this.imageProcessingConfiguration.colorCurves;
  56137. },
  56138. /**
  56139. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  56140. */
  56141. set: function (value) {
  56142. this.imageProcessingConfiguration.colorCurves = value;
  56143. },
  56144. enumerable: true,
  56145. configurable: true
  56146. });
  56147. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  56148. /**
  56149. * Gets wether the color curves effect is enabled.
  56150. */
  56151. get: function () {
  56152. return this.imageProcessingConfiguration.colorCurvesEnabled;
  56153. },
  56154. /**
  56155. * Sets wether the color curves effect is enabled.
  56156. */
  56157. set: function (value) {
  56158. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  56159. },
  56160. enumerable: true,
  56161. configurable: true
  56162. });
  56163. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  56164. /**
  56165. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  56166. */
  56167. get: function () {
  56168. return this.imageProcessingConfiguration.colorGradingTexture;
  56169. },
  56170. /**
  56171. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  56172. */
  56173. set: function (value) {
  56174. this.imageProcessingConfiguration.colorGradingTexture = value;
  56175. },
  56176. enumerable: true,
  56177. configurable: true
  56178. });
  56179. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  56180. /**
  56181. * Gets wether the color grading effect is enabled.
  56182. */
  56183. get: function () {
  56184. return this.imageProcessingConfiguration.colorGradingEnabled;
  56185. },
  56186. /**
  56187. * Gets wether the color grading effect is enabled.
  56188. */
  56189. set: function (value) {
  56190. this.imageProcessingConfiguration.colorGradingEnabled = value;
  56191. },
  56192. enumerable: true,
  56193. configurable: true
  56194. });
  56195. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  56196. /**
  56197. * Gets exposure used in the effect.
  56198. */
  56199. get: function () {
  56200. return this.imageProcessingConfiguration.exposure;
  56201. },
  56202. /**
  56203. * Sets exposure used in the effect.
  56204. */
  56205. set: function (value) {
  56206. this.imageProcessingConfiguration.exposure = value;
  56207. },
  56208. enumerable: true,
  56209. configurable: true
  56210. });
  56211. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  56212. /**
  56213. * Gets wether tonemapping is enabled or not.
  56214. */
  56215. get: function () {
  56216. return this._imageProcessingConfiguration.toneMappingEnabled;
  56217. },
  56218. /**
  56219. * Sets wether tonemapping is enabled or not
  56220. */
  56221. set: function (value) {
  56222. this._imageProcessingConfiguration.toneMappingEnabled = value;
  56223. },
  56224. enumerable: true,
  56225. configurable: true
  56226. });
  56227. ;
  56228. ;
  56229. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  56230. /**
  56231. * Gets contrast used in the effect.
  56232. */
  56233. get: function () {
  56234. return this.imageProcessingConfiguration.contrast;
  56235. },
  56236. /**
  56237. * Sets contrast used in the effect.
  56238. */
  56239. set: function (value) {
  56240. this.imageProcessingConfiguration.contrast = value;
  56241. },
  56242. enumerable: true,
  56243. configurable: true
  56244. });
  56245. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  56246. /**
  56247. * Gets Vignette stretch size.
  56248. */
  56249. get: function () {
  56250. return this.imageProcessingConfiguration.vignetteStretch;
  56251. },
  56252. /**
  56253. * Sets Vignette stretch size.
  56254. */
  56255. set: function (value) {
  56256. this.imageProcessingConfiguration.vignetteStretch = value;
  56257. },
  56258. enumerable: true,
  56259. configurable: true
  56260. });
  56261. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  56262. /**
  56263. * Gets Vignette centre X Offset.
  56264. */
  56265. get: function () {
  56266. return this.imageProcessingConfiguration.vignetteCentreX;
  56267. },
  56268. /**
  56269. * Sets Vignette centre X Offset.
  56270. */
  56271. set: function (value) {
  56272. this.imageProcessingConfiguration.vignetteCentreX = value;
  56273. },
  56274. enumerable: true,
  56275. configurable: true
  56276. });
  56277. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  56278. /**
  56279. * Gets Vignette centre Y Offset.
  56280. */
  56281. get: function () {
  56282. return this.imageProcessingConfiguration.vignetteCentreY;
  56283. },
  56284. /**
  56285. * Sets Vignette centre Y Offset.
  56286. */
  56287. set: function (value) {
  56288. this.imageProcessingConfiguration.vignetteCentreY = value;
  56289. },
  56290. enumerable: true,
  56291. configurable: true
  56292. });
  56293. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  56294. /**
  56295. * Gets Vignette weight or intensity of the vignette effect.
  56296. */
  56297. get: function () {
  56298. return this.imageProcessingConfiguration.vignetteWeight;
  56299. },
  56300. /**
  56301. * Sets Vignette weight or intensity of the vignette effect.
  56302. */
  56303. set: function (value) {
  56304. this.imageProcessingConfiguration.vignetteWeight = value;
  56305. },
  56306. enumerable: true,
  56307. configurable: true
  56308. });
  56309. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  56310. /**
  56311. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  56312. * if vignetteEnabled is set to true.
  56313. */
  56314. get: function () {
  56315. return this.imageProcessingConfiguration.vignetteColor;
  56316. },
  56317. /**
  56318. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  56319. * if vignetteEnabled is set to true.
  56320. */
  56321. set: function (value) {
  56322. this.imageProcessingConfiguration.vignetteColor = value;
  56323. },
  56324. enumerable: true,
  56325. configurable: true
  56326. });
  56327. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  56328. /**
  56329. * Gets Camera field of view used by the Vignette effect.
  56330. */
  56331. get: function () {
  56332. return this.imageProcessingConfiguration.vignetteCameraFov;
  56333. },
  56334. /**
  56335. * Sets Camera field of view used by the Vignette effect.
  56336. */
  56337. set: function (value) {
  56338. this.imageProcessingConfiguration.vignetteCameraFov = value;
  56339. },
  56340. enumerable: true,
  56341. configurable: true
  56342. });
  56343. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  56344. /**
  56345. * Gets the vignette blend mode allowing different kind of effect.
  56346. */
  56347. get: function () {
  56348. return this.imageProcessingConfiguration.vignetteBlendMode;
  56349. },
  56350. /**
  56351. * Sets the vignette blend mode allowing different kind of effect.
  56352. */
  56353. set: function (value) {
  56354. this.imageProcessingConfiguration.vignetteBlendMode = value;
  56355. },
  56356. enumerable: true,
  56357. configurable: true
  56358. });
  56359. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  56360. /**
  56361. * Gets wether the vignette effect is enabled.
  56362. */
  56363. get: function () {
  56364. return this.imageProcessingConfiguration.vignetteEnabled;
  56365. },
  56366. /**
  56367. * Sets wether the vignette effect is enabled.
  56368. */
  56369. set: function (value) {
  56370. this.imageProcessingConfiguration.vignetteEnabled = value;
  56371. },
  56372. enumerable: true,
  56373. configurable: true
  56374. });
  56375. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  56376. /**
  56377. * Gets wether the input of the processing is in Gamma or Linear Space.
  56378. */
  56379. get: function () {
  56380. return this._fromLinearSpace;
  56381. },
  56382. /**
  56383. * Sets wether the input of the processing is in Gamma or Linear Space.
  56384. */
  56385. set: function (value) {
  56386. if (this._fromLinearSpace === value) {
  56387. return;
  56388. }
  56389. this._fromLinearSpace = value;
  56390. this._updateParameters();
  56391. },
  56392. enumerable: true,
  56393. configurable: true
  56394. });
  56395. ImageProcessingPostProcess.prototype.getClassName = function () {
  56396. return "ImageProcessingPostProcess";
  56397. };
  56398. ImageProcessingPostProcess.prototype._updateParameters = function () {
  56399. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  56400. this.imageProcessingConfiguration.prepareDefines(this._defines);
  56401. var defines = "";
  56402. for (var define in this._defines) {
  56403. if (this._defines[define]) {
  56404. defines += "#define " + define + ";\r\n";
  56405. }
  56406. }
  56407. var samplers = ["textureSampler"];
  56408. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  56409. var uniforms = ["scale"];
  56410. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  56411. this.updateEffect(defines, uniforms, samplers);
  56412. };
  56413. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  56414. _super.prototype.dispose.call(this, camera);
  56415. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  56416. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  56417. }
  56418. this.imageProcessingConfiguration.applyByPostProcess = false;
  56419. };
  56420. __decorate([
  56421. BABYLON.serialize()
  56422. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  56423. return ImageProcessingPostProcess;
  56424. }(BABYLON.PostProcess));
  56425. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  56426. })(BABYLON || (BABYLON = {}));
  56427. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  56428. var BABYLON;
  56429. (function (BABYLON) {
  56430. var BlurPostProcess = (function (_super) {
  56431. __extends(BlurPostProcess, _super);
  56432. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  56433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56434. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56435. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  56436. _this.direction = direction;
  56437. _this._packedFloat = false;
  56438. _this.onApplyObservable.add(function (effect) {
  56439. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  56440. });
  56441. _this.kernel = kernel;
  56442. return _this;
  56443. }
  56444. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  56445. /**
  56446. * Gets the length in pixels of the blur sample region
  56447. */
  56448. get: function () {
  56449. return this._idealKernel;
  56450. },
  56451. /**
  56452. * Sets the length in pixels of the blur sample region
  56453. */
  56454. set: function (v) {
  56455. if (this._idealKernel === v) {
  56456. return;
  56457. }
  56458. v = Math.max(v, 1);
  56459. this._idealKernel = v;
  56460. this._kernel = this._nearestBestKernel(v);
  56461. this._updateParameters();
  56462. },
  56463. enumerable: true,
  56464. configurable: true
  56465. });
  56466. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  56467. /**
  56468. * Gets wether or not the blur is unpacking/repacking floats
  56469. */
  56470. get: function () {
  56471. return this._packedFloat;
  56472. },
  56473. /**
  56474. * Sets wether or not the blur needs to unpack/repack floats
  56475. */
  56476. set: function (v) {
  56477. if (this._packedFloat === v) {
  56478. return;
  56479. }
  56480. this._packedFloat = v;
  56481. this._updateParameters();
  56482. },
  56483. enumerable: true,
  56484. configurable: true
  56485. });
  56486. BlurPostProcess.prototype._updateParameters = function () {
  56487. // Generate sampling offsets and weights
  56488. var N = this._kernel;
  56489. var centerIndex = (N - 1) / 2;
  56490. // Generate Gaussian sampling weights over kernel
  56491. var offsets = [];
  56492. var weights = [];
  56493. var totalWeight = 0;
  56494. for (var i = 0; i < N; i++) {
  56495. var u = i / (N - 1);
  56496. var w = this._gaussianWeight(u * 2.0 - 1);
  56497. offsets[i] = (i - centerIndex);
  56498. weights[i] = w;
  56499. totalWeight += w;
  56500. }
  56501. // Normalize weights
  56502. for (var i = 0; i < weights.length; i++) {
  56503. weights[i] /= totalWeight;
  56504. }
  56505. // Optimize: combine samples to take advantage of hardware linear sampling
  56506. // Walk from left to center, combining pairs (symmetrically)
  56507. var linearSamplingWeights = [];
  56508. var linearSamplingOffsets = [];
  56509. var linearSamplingMap = [];
  56510. for (var i = 0; i <= centerIndex; i += 2) {
  56511. var j = Math.min(i + 1, Math.floor(centerIndex));
  56512. var singleCenterSample = i === j;
  56513. if (singleCenterSample) {
  56514. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  56515. }
  56516. else {
  56517. var sharedCell = j === centerIndex;
  56518. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  56519. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  56520. if (offsetLinear === 0) {
  56521. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  56522. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  56523. }
  56524. else {
  56525. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  56526. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  56527. }
  56528. }
  56529. }
  56530. for (var i = 0; i < linearSamplingMap.length; i++) {
  56531. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  56532. linearSamplingWeights[i] = linearSamplingMap[i].w;
  56533. }
  56534. // Replace with optimized
  56535. offsets = linearSamplingOffsets;
  56536. weights = linearSamplingWeights;
  56537. // Generate shaders
  56538. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  56539. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  56540. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  56541. var defines = "";
  56542. for (var i = 0; i < varyingCount; i++) {
  56543. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  56544. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  56545. }
  56546. var depCount = 0;
  56547. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  56548. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  56549. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  56550. depCount++;
  56551. }
  56552. if (this.packedFloat) {
  56553. defines += "#define PACKEDFLOAT 1";
  56554. }
  56555. this.updateEffect(defines, null, null, {
  56556. varyingCount: varyingCount,
  56557. depCount: depCount
  56558. });
  56559. };
  56560. /**
  56561. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  56562. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  56563. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  56564. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  56565. * The gaps between physical kernels are compensated for in the weighting of the samples
  56566. * @param idealKernel Ideal blur kernel.
  56567. * @return Nearest best kernel.
  56568. */
  56569. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  56570. var v = Math.round(idealKernel);
  56571. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  56572. var k = _a[_i];
  56573. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  56574. return Math.max(k, 3);
  56575. }
  56576. }
  56577. return Math.max(v, 3);
  56578. };
  56579. /**
  56580. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  56581. * @param x The point on the Gaussian distribution to sample.
  56582. * @return the value of the Gaussian function at x.
  56583. */
  56584. BlurPostProcess.prototype._gaussianWeight = function (x) {
  56585. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  56586. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  56587. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  56588. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  56589. // truncated at around 1.3% of peak strength.
  56590. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  56591. var sigma = (1 / 3);
  56592. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  56593. var exponent = -((x * x) / (2.0 * sigma * sigma));
  56594. var weight = (1.0 / denominator) * Math.exp(exponent);
  56595. return weight;
  56596. };
  56597. /**
  56598. * Generates a string that can be used as a floating point number in GLSL.
  56599. * @param x Value to print.
  56600. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  56601. * @return GLSL float string.
  56602. */
  56603. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  56604. if (decimalFigures === void 0) { decimalFigures = 8; }
  56605. return x.toFixed(decimalFigures).replace(/0+$/, '');
  56606. };
  56607. return BlurPostProcess;
  56608. }(BABYLON.PostProcess));
  56609. BABYLON.BlurPostProcess = BlurPostProcess;
  56610. })(BABYLON || (BABYLON = {}));
  56611. //# sourceMappingURL=babylon.blurPostProcess.js.map
  56612. /// <reference path="..\babylon.node.ts" />
  56613. var BABYLON;
  56614. (function (BABYLON) {
  56615. var Bone = (function (_super) {
  56616. __extends(Bone, _super);
  56617. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  56618. if (parentBone === void 0) { parentBone = null; }
  56619. var _this = _super.call(this, name, skeleton.getScene()) || this;
  56620. _this.name = name;
  56621. _this.children = new Array();
  56622. _this.animations = new Array();
  56623. _this._worldTransform = new BABYLON.Matrix();
  56624. _this._absoluteTransform = new BABYLON.Matrix();
  56625. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  56626. _this._scaleMatrix = BABYLON.Matrix.Identity();
  56627. _this._scaleVector = BABYLON.Vector3.One();
  56628. _this._negateScaleChildren = BABYLON.Vector3.One();
  56629. _this._scalingDeterminant = 1;
  56630. _this._skeleton = skeleton;
  56631. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  56632. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  56633. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  56634. _this._index = index;
  56635. skeleton.bones.push(_this);
  56636. _this.setParent(parentBone, false);
  56637. _this._updateDifferenceMatrix();
  56638. return _this;
  56639. }
  56640. Object.defineProperty(Bone.prototype, "_matrix", {
  56641. get: function () {
  56642. return this._localMatrix;
  56643. },
  56644. set: function (val) {
  56645. if (this._localMatrix) {
  56646. this._localMatrix.copyFrom(val);
  56647. }
  56648. else {
  56649. this._localMatrix = val;
  56650. }
  56651. },
  56652. enumerable: true,
  56653. configurable: true
  56654. });
  56655. // Members
  56656. Bone.prototype.getSkeleton = function () {
  56657. return this._skeleton;
  56658. };
  56659. Bone.prototype.getParent = function () {
  56660. return this._parent;
  56661. };
  56662. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  56663. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  56664. if (this._parent === parent) {
  56665. return;
  56666. }
  56667. if (this._parent) {
  56668. var index = this._parent.children.indexOf(this);
  56669. if (index !== -1) {
  56670. this._parent.children.splice(index);
  56671. }
  56672. }
  56673. this._parent = parent;
  56674. if (this._parent) {
  56675. this._parent.children.push(this);
  56676. }
  56677. if (updateDifferenceMatrix) {
  56678. this._updateDifferenceMatrix();
  56679. }
  56680. };
  56681. Bone.prototype.getLocalMatrix = function () {
  56682. return this._localMatrix;
  56683. };
  56684. Bone.prototype.getBaseMatrix = function () {
  56685. return this._baseMatrix;
  56686. };
  56687. Bone.prototype.getRestPose = function () {
  56688. return this._restPose;
  56689. };
  56690. Bone.prototype.returnToRest = function () {
  56691. this.updateMatrix(this._restPose.clone());
  56692. };
  56693. Bone.prototype.getWorldMatrix = function () {
  56694. return this._worldTransform;
  56695. };
  56696. Bone.prototype.getInvertedAbsoluteTransform = function () {
  56697. return this._invertedAbsoluteTransform;
  56698. };
  56699. Bone.prototype.getAbsoluteTransform = function () {
  56700. return this._absoluteTransform;
  56701. };
  56702. Object.defineProperty(Bone.prototype, "position", {
  56703. // Properties (matches AbstractMesh properties)
  56704. get: function () {
  56705. return this.getPosition();
  56706. },
  56707. set: function (newPosition) {
  56708. this.setPosition(newPosition);
  56709. },
  56710. enumerable: true,
  56711. configurable: true
  56712. });
  56713. Object.defineProperty(Bone.prototype, "rotation", {
  56714. get: function () {
  56715. return this.getRotation();
  56716. },
  56717. set: function (newRotation) {
  56718. this.setRotation(newRotation);
  56719. },
  56720. enumerable: true,
  56721. configurable: true
  56722. });
  56723. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  56724. get: function () {
  56725. return this.getRotationQuaternion();
  56726. },
  56727. set: function (newRotation) {
  56728. this.setRotationQuaternion(newRotation);
  56729. },
  56730. enumerable: true,
  56731. configurable: true
  56732. });
  56733. Object.defineProperty(Bone.prototype, "scaling", {
  56734. get: function () {
  56735. return this.getScale();
  56736. },
  56737. set: function (newScaling) {
  56738. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  56739. },
  56740. enumerable: true,
  56741. configurable: true
  56742. });
  56743. // Methods
  56744. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  56745. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  56746. this._baseMatrix = matrix.clone();
  56747. this._localMatrix = matrix.clone();
  56748. this._skeleton._markAsDirty();
  56749. if (updateDifferenceMatrix) {
  56750. this._updateDifferenceMatrix();
  56751. }
  56752. };
  56753. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  56754. if (!rootMatrix) {
  56755. rootMatrix = this._baseMatrix;
  56756. }
  56757. if (this._parent) {
  56758. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  56759. }
  56760. else {
  56761. this._absoluteTransform.copyFrom(rootMatrix);
  56762. }
  56763. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  56764. for (var index = 0; index < this.children.length; index++) {
  56765. this.children[index]._updateDifferenceMatrix();
  56766. }
  56767. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  56768. };
  56769. Bone.prototype.markAsDirty = function () {
  56770. this._currentRenderId++;
  56771. this._skeleton._markAsDirty();
  56772. };
  56773. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  56774. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  56775. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  56776. // all animation may be coming from a library skeleton, so may need to create animation
  56777. if (this.animations.length === 0) {
  56778. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  56779. this.animations[0].setKeys([]);
  56780. }
  56781. // get animation info / verify there is such a range from the source bone
  56782. var sourceRange = source.animations[0].getRange(rangeName);
  56783. if (!sourceRange) {
  56784. return false;
  56785. }
  56786. var from = sourceRange.from;
  56787. var to = sourceRange.to;
  56788. var sourceKeys = source.animations[0].getKeys();
  56789. // rescaling prep
  56790. var sourceBoneLength = source.length;
  56791. var sourceParent = source.getParent();
  56792. var parent = this.getParent();
  56793. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  56794. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  56795. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  56796. var destKeys = this.animations[0].getKeys();
  56797. // loop vars declaration
  56798. var orig;
  56799. var origTranslation;
  56800. var mat;
  56801. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  56802. orig = sourceKeys[key];
  56803. if (orig.frame >= from && orig.frame <= to) {
  56804. if (rescaleAsRequired) {
  56805. mat = orig.value.clone();
  56806. // scale based on parent ratio, when bone has parent
  56807. if (parentScalingReqd) {
  56808. origTranslation = mat.getTranslation();
  56809. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  56810. // scale based on skeleton dimension ratio when root bone, and value is passed
  56811. }
  56812. else if (dimensionsScalingReqd) {
  56813. origTranslation = mat.getTranslation();
  56814. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  56815. // use original when root bone, and no data for skelDimensionsRatio
  56816. }
  56817. else {
  56818. mat = orig.value;
  56819. }
  56820. }
  56821. else {
  56822. mat = orig.value;
  56823. }
  56824. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  56825. }
  56826. }
  56827. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  56828. return true;
  56829. };
  56830. /**
  56831. * Translate the bone in local or world space.
  56832. * @param vec The amount to translate the bone.
  56833. * @param space The space that the translation is in.
  56834. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56835. */
  56836. Bone.prototype.translate = function (vec, space, mesh) {
  56837. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56838. var lm = this.getLocalMatrix();
  56839. if (space == BABYLON.Space.LOCAL) {
  56840. lm.m[12] += vec.x;
  56841. lm.m[13] += vec.y;
  56842. lm.m[14] += vec.z;
  56843. }
  56844. else {
  56845. var wm;
  56846. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56847. if (mesh) {
  56848. wm = mesh.getWorldMatrix();
  56849. }
  56850. this._skeleton.computeAbsoluteTransforms();
  56851. var tmat = Bone._tmpMats[0];
  56852. var tvec = Bone._tmpVecs[0];
  56853. if (mesh) {
  56854. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56855. tmat.multiplyToRef(wm, tmat);
  56856. }
  56857. else {
  56858. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56859. }
  56860. tmat.m[12] = 0;
  56861. tmat.m[13] = 0;
  56862. tmat.m[14] = 0;
  56863. tmat.invert();
  56864. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  56865. lm.m[12] += tvec.x;
  56866. lm.m[13] += tvec.y;
  56867. lm.m[14] += tvec.z;
  56868. }
  56869. this.markAsDirty();
  56870. };
  56871. /**
  56872. * Set the postion of the bone in local or world space.
  56873. * @param position The position to set the bone.
  56874. * @param space The space that the position is in.
  56875. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56876. */
  56877. Bone.prototype.setPosition = function (position, space, mesh) {
  56878. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56879. var lm = this.getLocalMatrix();
  56880. if (space == BABYLON.Space.LOCAL) {
  56881. lm.m[12] = position.x;
  56882. lm.m[13] = position.y;
  56883. lm.m[14] = position.z;
  56884. }
  56885. else {
  56886. var wm;
  56887. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56888. if (mesh) {
  56889. wm = mesh.getWorldMatrix();
  56890. }
  56891. this._skeleton.computeAbsoluteTransforms();
  56892. var tmat = Bone._tmpMats[0];
  56893. var vec = Bone._tmpVecs[0];
  56894. if (mesh) {
  56895. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56896. tmat.multiplyToRef(wm, tmat);
  56897. }
  56898. else {
  56899. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56900. }
  56901. tmat.invert();
  56902. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  56903. lm.m[12] = vec.x;
  56904. lm.m[13] = vec.y;
  56905. lm.m[14] = vec.z;
  56906. }
  56907. this.markAsDirty();
  56908. };
  56909. /**
  56910. * Set the absolute postion of the bone (world space).
  56911. * @param position The position to set the bone.
  56912. * @param mesh The mesh that this bone is attached to.
  56913. */
  56914. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  56915. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  56916. };
  56917. /**
  56918. * Set the scale of the bone on the x, y and z axes.
  56919. * @param x The scale of the bone on the x axis.
  56920. * @param x The scale of the bone on the y axis.
  56921. * @param z The scale of the bone on the z axis.
  56922. * @param scaleChildren Set this to true if children of the bone should be scaled.
  56923. */
  56924. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  56925. if (scaleChildren === void 0) { scaleChildren = false; }
  56926. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  56927. if (!scaleChildren) {
  56928. this._negateScaleChildren.x = 1 / x;
  56929. this._negateScaleChildren.y = 1 / y;
  56930. this._negateScaleChildren.z = 1 / z;
  56931. }
  56932. this._syncScaleVector();
  56933. }
  56934. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  56935. };
  56936. /**
  56937. * Scale the bone on the x, y and z axes.
  56938. * @param x The amount to scale the bone on the x axis.
  56939. * @param x The amount to scale the bone on the y axis.
  56940. * @param z The amount to scale the bone on the z axis.
  56941. * @param scaleChildren Set this to true if children of the bone should be scaled.
  56942. */
  56943. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  56944. if (scaleChildren === void 0) { scaleChildren = false; }
  56945. var locMat = this.getLocalMatrix();
  56946. var origLocMat = Bone._tmpMats[0];
  56947. origLocMat.copyFrom(locMat);
  56948. var origLocMatInv = Bone._tmpMats[1];
  56949. origLocMatInv.copyFrom(origLocMat);
  56950. origLocMatInv.invert();
  56951. var scaleMat = Bone._tmpMats[2];
  56952. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  56953. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  56954. this._scaleVector.x *= x;
  56955. this._scaleVector.y *= y;
  56956. this._scaleVector.z *= z;
  56957. locMat.multiplyToRef(origLocMatInv, locMat);
  56958. locMat.multiplyToRef(scaleMat, locMat);
  56959. locMat.multiplyToRef(origLocMat, locMat);
  56960. var parent = this.getParent();
  56961. if (parent) {
  56962. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  56963. }
  56964. else {
  56965. this.getAbsoluteTransform().copyFrom(locMat);
  56966. }
  56967. var len = this.children.length;
  56968. scaleMat.invert();
  56969. for (var i = 0; i < len; i++) {
  56970. var child = this.children[i];
  56971. var cm = child.getLocalMatrix();
  56972. cm.multiplyToRef(scaleMat, cm);
  56973. var lm = child.getLocalMatrix();
  56974. lm.m[12] *= x;
  56975. lm.m[13] *= y;
  56976. lm.m[14] *= z;
  56977. }
  56978. this.computeAbsoluteTransforms();
  56979. if (scaleChildren) {
  56980. for (var i = 0; i < len; i++) {
  56981. this.children[i].scale(x, y, z, scaleChildren);
  56982. }
  56983. }
  56984. this.markAsDirty();
  56985. };
  56986. /**
  56987. * Set the yaw, pitch, and roll of the bone in local or world space.
  56988. * @param yaw The rotation of the bone on the y axis.
  56989. * @param pitch The rotation of the bone on the x axis.
  56990. * @param roll The rotation of the bone on the z axis.
  56991. * @param space The space that the axes of rotation are in.
  56992. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56993. */
  56994. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  56995. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56996. var rotMat = Bone._tmpMats[0];
  56997. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  56998. var rotMatInv = Bone._tmpMats[1];
  56999. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57000. rotMatInv.multiplyToRef(rotMat, rotMat);
  57001. this._rotateWithMatrix(rotMat, space, mesh);
  57002. };
  57003. /**
  57004. * Rotate the bone on an axis in local or world space.
  57005. * @param axis The axis to rotate the bone on.
  57006. * @param amount The amount to rotate the bone.
  57007. * @param space The space that the axis is in.
  57008. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57009. */
  57010. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  57011. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57012. var rmat = Bone._tmpMats[0];
  57013. rmat.m[12] = 0;
  57014. rmat.m[13] = 0;
  57015. rmat.m[14] = 0;
  57016. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  57017. this._rotateWithMatrix(rmat, space, mesh);
  57018. };
  57019. /**
  57020. * Set the rotation of the bone to a particular axis angle in local or world space.
  57021. * @param axis The axis to rotate the bone on.
  57022. * @param angle The angle that the bone should be rotated to.
  57023. * @param space The space that the axis is in.
  57024. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57025. */
  57026. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  57027. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57028. var rotMat = Bone._tmpMats[0];
  57029. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  57030. var rotMatInv = Bone._tmpMats[1];
  57031. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57032. rotMatInv.multiplyToRef(rotMat, rotMat);
  57033. this._rotateWithMatrix(rotMat, space, mesh);
  57034. };
  57035. /**
  57036. * Set the euler rotation of the bone in local of world space.
  57037. * @param rotation The euler rotation that the bone should be set to.
  57038. * @param space The space that the rotation is in.
  57039. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57040. */
  57041. Bone.prototype.setRotation = function (rotation, space, mesh) {
  57042. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57043. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  57044. };
  57045. /**
  57046. * Set the quaternion rotation of the bone in local of world space.
  57047. * @param quat The quaternion rotation that the bone should be set to.
  57048. * @param space The space that the rotation is in.
  57049. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57050. */
  57051. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  57052. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57053. var rotMatInv = Bone._tmpMats[0];
  57054. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57055. var rotMat = Bone._tmpMats[1];
  57056. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  57057. rotMatInv.multiplyToRef(rotMat, rotMat);
  57058. this._rotateWithMatrix(rotMat, space, mesh);
  57059. };
  57060. /**
  57061. * Set the rotation matrix of the bone in local of world space.
  57062. * @param rotMat The rotation matrix that the bone should be set to.
  57063. * @param space The space that the rotation is in.
  57064. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57065. */
  57066. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  57067. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57068. var rotMatInv = Bone._tmpMats[0];
  57069. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57070. var rotMat2 = Bone._tmpMats[1];
  57071. rotMat2.copyFrom(rotMat);
  57072. rotMatInv.multiplyToRef(rotMat, rotMat2);
  57073. this._rotateWithMatrix(rotMat2, space, mesh);
  57074. };
  57075. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  57076. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57077. var lmat = this.getLocalMatrix();
  57078. var lx = lmat.m[12];
  57079. var ly = lmat.m[13];
  57080. var lz = lmat.m[14];
  57081. var parent = this.getParent();
  57082. var parentScale = Bone._tmpMats[3];
  57083. var parentScaleInv = Bone._tmpMats[4];
  57084. if (parent) {
  57085. if (space == BABYLON.Space.WORLD) {
  57086. if (mesh) {
  57087. parentScale.copyFrom(mesh.getWorldMatrix());
  57088. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  57089. }
  57090. else {
  57091. parentScale.copyFrom(parent.getAbsoluteTransform());
  57092. }
  57093. }
  57094. else {
  57095. parentScale = parent._scaleMatrix;
  57096. }
  57097. parentScaleInv.copyFrom(parentScale);
  57098. parentScaleInv.invert();
  57099. lmat.multiplyToRef(parentScale, lmat);
  57100. lmat.multiplyToRef(rmat, lmat);
  57101. lmat.multiplyToRef(parentScaleInv, lmat);
  57102. }
  57103. else {
  57104. if (space == BABYLON.Space.WORLD && mesh) {
  57105. parentScale.copyFrom(mesh.getWorldMatrix());
  57106. parentScaleInv.copyFrom(parentScale);
  57107. parentScaleInv.invert();
  57108. lmat.multiplyToRef(parentScale, lmat);
  57109. lmat.multiplyToRef(rmat, lmat);
  57110. lmat.multiplyToRef(parentScaleInv, lmat);
  57111. }
  57112. else {
  57113. lmat.multiplyToRef(rmat, lmat);
  57114. }
  57115. }
  57116. lmat.m[12] = lx;
  57117. lmat.m[13] = ly;
  57118. lmat.m[14] = lz;
  57119. this.computeAbsoluteTransforms();
  57120. this.markAsDirty();
  57121. };
  57122. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  57123. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57124. if (space == BABYLON.Space.WORLD) {
  57125. var scaleMatrix = Bone._tmpMats[2];
  57126. scaleMatrix.copyFrom(this._scaleMatrix);
  57127. rotMatInv.copyFrom(this.getAbsoluteTransform());
  57128. if (mesh) {
  57129. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  57130. var meshScale = Bone._tmpMats[3];
  57131. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  57132. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  57133. }
  57134. rotMatInv.invert();
  57135. scaleMatrix.m[0] *= this._scalingDeterminant;
  57136. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  57137. }
  57138. else {
  57139. rotMatInv.copyFrom(this.getLocalMatrix());
  57140. rotMatInv.invert();
  57141. var scaleMatrix = Bone._tmpMats[2];
  57142. scaleMatrix.copyFrom(this._scaleMatrix);
  57143. if (this._parent) {
  57144. var pscaleMatrix = Bone._tmpMats[3];
  57145. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  57146. pscaleMatrix.invert();
  57147. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  57148. }
  57149. else {
  57150. scaleMatrix.m[0] *= this._scalingDeterminant;
  57151. }
  57152. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  57153. }
  57154. };
  57155. /**
  57156. * Get the scale of the bone
  57157. * @returns the scale of the bone
  57158. */
  57159. Bone.prototype.getScale = function () {
  57160. return this._scaleVector.clone();
  57161. };
  57162. /**
  57163. * Copy the scale of the bone to a vector3.
  57164. * @param result The vector3 to copy the scale to
  57165. */
  57166. Bone.prototype.getScaleToRef = function (result) {
  57167. result.copyFrom(this._scaleVector);
  57168. };
  57169. /**
  57170. * Get the position of the bone in local or world space.
  57171. * @param space The space that the returned position is in.
  57172. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57173. * @returns The position of the bone
  57174. */
  57175. Bone.prototype.getPosition = function (space, mesh) {
  57176. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57177. var pos = BABYLON.Vector3.Zero();
  57178. this.getPositionToRef(space, mesh, pos);
  57179. return pos;
  57180. };
  57181. /**
  57182. * Copy the position of the bone to a vector3 in local or world space.
  57183. * @param space The space that the returned position is in.
  57184. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57185. * @param result The vector3 to copy the position to.
  57186. */
  57187. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  57188. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57189. if (space == BABYLON.Space.LOCAL) {
  57190. var lm = this.getLocalMatrix();
  57191. result.x = lm.m[12];
  57192. result.y = lm.m[13];
  57193. result.z = lm.m[14];
  57194. }
  57195. else {
  57196. var wm;
  57197. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57198. if (mesh) {
  57199. wm = mesh.getWorldMatrix();
  57200. }
  57201. this._skeleton.computeAbsoluteTransforms();
  57202. var tmat = Bone._tmpMats[0];
  57203. if (mesh) {
  57204. tmat.copyFrom(this.getAbsoluteTransform());
  57205. tmat.multiplyToRef(wm, tmat);
  57206. }
  57207. else {
  57208. tmat = this.getAbsoluteTransform();
  57209. }
  57210. result.x = tmat.m[12];
  57211. result.y = tmat.m[13];
  57212. result.z = tmat.m[14];
  57213. }
  57214. };
  57215. /**
  57216. * Get the absolute position of the bone (world space).
  57217. * @param mesh The mesh that this bone is attached to.
  57218. * @returns The absolute position of the bone
  57219. */
  57220. Bone.prototype.getAbsolutePosition = function (mesh) {
  57221. var pos = BABYLON.Vector3.Zero();
  57222. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  57223. return pos;
  57224. };
  57225. /**
  57226. * Copy the absolute position of the bone (world space) to the result param.
  57227. * @param mesh The mesh that this bone is attached to.
  57228. * @param result The vector3 to copy the absolute position to.
  57229. */
  57230. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  57231. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  57232. };
  57233. /**
  57234. * Compute the absolute transforms of this bone and its children.
  57235. */
  57236. Bone.prototype.computeAbsoluteTransforms = function () {
  57237. if (this._parent) {
  57238. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  57239. }
  57240. else {
  57241. this._absoluteTransform.copyFrom(this._localMatrix);
  57242. var poseMatrix = this._skeleton.getPoseMatrix();
  57243. if (poseMatrix) {
  57244. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  57245. }
  57246. }
  57247. var children = this.children;
  57248. var len = children.length;
  57249. for (var i = 0; i < len; i++) {
  57250. children[i].computeAbsoluteTransforms();
  57251. }
  57252. };
  57253. Bone.prototype._syncScaleVector = function () {
  57254. var lm = this.getLocalMatrix();
  57255. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  57256. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  57257. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  57258. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  57259. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  57260. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  57261. this._scaleVector.x = xs * Math.sqrt(xsq);
  57262. this._scaleVector.y = ys * Math.sqrt(ysq);
  57263. this._scaleVector.z = zs * Math.sqrt(zsq);
  57264. if (this._parent) {
  57265. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  57266. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  57267. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  57268. }
  57269. 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);
  57270. };
  57271. /**
  57272. * Get the world direction from an axis that is in the local space of the bone.
  57273. * @param localAxis The local direction that is used to compute the world direction.
  57274. * @param mesh The mesh that this bone is attached to.
  57275. * @returns The world direction
  57276. */
  57277. Bone.prototype.getDirection = function (localAxis, mesh) {
  57278. var result = BABYLON.Vector3.Zero();
  57279. this.getDirectionToRef(localAxis, mesh, result);
  57280. return result;
  57281. };
  57282. /**
  57283. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  57284. * @param localAxis The local direction that is used to compute the world direction.
  57285. * @param mesh The mesh that this bone is attached to.
  57286. * @param result The vector3 that the world direction will be copied to.
  57287. */
  57288. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  57289. var wm;
  57290. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57291. if (mesh) {
  57292. wm = mesh.getWorldMatrix();
  57293. }
  57294. this._skeleton.computeAbsoluteTransforms();
  57295. var mat = Bone._tmpMats[0];
  57296. mat.copyFrom(this.getAbsoluteTransform());
  57297. if (mesh) {
  57298. mat.multiplyToRef(wm, mat);
  57299. }
  57300. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  57301. result.normalize();
  57302. };
  57303. /**
  57304. * Get the euler rotation of the bone in local or world space.
  57305. * @param space The space that the rotation should be in.
  57306. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57307. * @returns The euler rotation
  57308. */
  57309. Bone.prototype.getRotation = function (space, mesh) {
  57310. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57311. var result = BABYLON.Vector3.Zero();
  57312. this.getRotationToRef(space, mesh, result);
  57313. return result;
  57314. };
  57315. /**
  57316. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  57317. * @param space The space that the rotation should be in.
  57318. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57319. * @param result The vector3 that the rotation should be copied to.
  57320. */
  57321. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  57322. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57323. var quat = Bone._tmpQuat;
  57324. this.getRotationQuaternionToRef(space, mesh, quat);
  57325. quat.toEulerAnglesToRef(result);
  57326. };
  57327. /**
  57328. * Get the quaternion rotation of the bone in either local or world space.
  57329. * @param space The space that the rotation should be in.
  57330. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57331. * @returns The quaternion rotation
  57332. */
  57333. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  57334. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57335. var result = BABYLON.Quaternion.Identity();
  57336. this.getRotationQuaternionToRef(space, mesh, result);
  57337. return result;
  57338. };
  57339. /**
  57340. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  57341. * @param space The space that the rotation should be in.
  57342. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57343. * @param result The quaternion that the rotation should be copied to.
  57344. */
  57345. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  57346. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57347. if (space == BABYLON.Space.LOCAL) {
  57348. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  57349. }
  57350. else {
  57351. var mat = Bone._tmpMats[0];
  57352. var amat = this.getAbsoluteTransform();
  57353. if (mesh) {
  57354. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  57355. }
  57356. else {
  57357. mat.copyFrom(amat);
  57358. }
  57359. mat.m[0] *= this._scalingDeterminant;
  57360. mat.m[1] *= this._scalingDeterminant;
  57361. mat.m[2] *= this._scalingDeterminant;
  57362. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  57363. }
  57364. };
  57365. /**
  57366. * Get the rotation matrix of the bone in local or world space.
  57367. * @param space The space that the rotation should be in.
  57368. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57369. * @returns The rotation matrix
  57370. */
  57371. Bone.prototype.getRotationMatrix = function (space, mesh) {
  57372. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57373. var result = BABYLON.Matrix.Identity();
  57374. this.getRotationMatrixToRef(space, mesh, result);
  57375. return result;
  57376. };
  57377. /**
  57378. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  57379. * @param space The space that the rotation should be in.
  57380. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57381. * @param result The quaternion that the rotation should be copied to.
  57382. */
  57383. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  57384. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57385. if (space == BABYLON.Space.LOCAL) {
  57386. this.getLocalMatrix().getRotationMatrixToRef(result);
  57387. }
  57388. else {
  57389. var mat = Bone._tmpMats[0];
  57390. var amat = this.getAbsoluteTransform();
  57391. if (mesh) {
  57392. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  57393. }
  57394. else {
  57395. mat.copyFrom(amat);
  57396. }
  57397. mat.m[0] *= this._scalingDeterminant;
  57398. mat.m[1] *= this._scalingDeterminant;
  57399. mat.m[2] *= this._scalingDeterminant;
  57400. mat.getRotationMatrixToRef(result);
  57401. }
  57402. };
  57403. /**
  57404. * Get the world position of a point that is in the local space of the bone.
  57405. * @param position The local position
  57406. * @param mesh The mesh that this bone is attached to.
  57407. * @returns The world position
  57408. */
  57409. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  57410. var result = BABYLON.Vector3.Zero();
  57411. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  57412. return result;
  57413. };
  57414. /**
  57415. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  57416. * @param position The local position
  57417. * @param mesh The mesh that this bone is attached to.
  57418. * @param result The vector3 that the world position should be copied to.
  57419. */
  57420. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  57421. var wm;
  57422. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57423. if (mesh) {
  57424. wm = mesh.getWorldMatrix();
  57425. }
  57426. this._skeleton.computeAbsoluteTransforms();
  57427. var tmat = Bone._tmpMats[0];
  57428. if (mesh) {
  57429. tmat.copyFrom(this.getAbsoluteTransform());
  57430. tmat.multiplyToRef(wm, tmat);
  57431. }
  57432. else {
  57433. tmat = this.getAbsoluteTransform();
  57434. }
  57435. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  57436. };
  57437. /**
  57438. * Get the local position of a point that is in world space.
  57439. * @param position The world position
  57440. * @param mesh The mesh that this bone is attached to.
  57441. * @returns The local position
  57442. */
  57443. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  57444. var result = BABYLON.Vector3.Zero();
  57445. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  57446. return result;
  57447. };
  57448. /**
  57449. * Get the local position of a point that is in world space and copy it to the result param.
  57450. * @param position The world position
  57451. * @param mesh The mesh that this bone is attached to.
  57452. * @param result The vector3 that the local position should be copied to.
  57453. */
  57454. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  57455. var wm;
  57456. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57457. if (mesh) {
  57458. wm = mesh.getWorldMatrix();
  57459. }
  57460. this._skeleton.computeAbsoluteTransforms();
  57461. var tmat = Bone._tmpMats[0];
  57462. tmat.copyFrom(this.getAbsoluteTransform());
  57463. if (mesh) {
  57464. tmat.multiplyToRef(wm, tmat);
  57465. }
  57466. tmat.invert();
  57467. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  57468. };
  57469. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57470. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  57471. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57472. return Bone;
  57473. }(BABYLON.Node));
  57474. BABYLON.Bone = Bone;
  57475. })(BABYLON || (BABYLON = {}));
  57476. //# sourceMappingURL=babylon.bone.js.map
  57477. var BABYLON;
  57478. (function (BABYLON) {
  57479. var BoneIKController = (function () {
  57480. function BoneIKController(mesh, bone, options) {
  57481. this.targetPosition = BABYLON.Vector3.Zero();
  57482. this.poleTargetPosition = BABYLON.Vector3.Zero();
  57483. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  57484. this.poleAngle = 0;
  57485. this.slerpAmount = 1;
  57486. this._bone1Quat = BABYLON.Quaternion.Identity();
  57487. this._bone1Mat = BABYLON.Matrix.Identity();
  57488. this._bone2Ang = Math.PI;
  57489. this._maxAngle = Math.PI;
  57490. this._rightHandedSystem = false;
  57491. this._bendAxis = BABYLON.Vector3.Right();
  57492. this._slerping = false;
  57493. this._adjustRoll = 0;
  57494. this._bone2 = bone;
  57495. this._bone1 = bone.getParent();
  57496. this.mesh = mesh;
  57497. var bonePos = bone.getPosition();
  57498. if (bone.getAbsoluteTransform().determinant() > 0) {
  57499. this._rightHandedSystem = true;
  57500. this._bendAxis.x = 0;
  57501. this._bendAxis.y = 0;
  57502. this._bendAxis.z = -1;
  57503. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  57504. this._adjustRoll = Math.PI * .5;
  57505. this._bendAxis.z = 1;
  57506. }
  57507. }
  57508. if (this._bone1.length) {
  57509. var boneScale1 = this._bone1.getScale();
  57510. var boneScale2 = this._bone2.getScale();
  57511. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  57512. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  57513. }
  57514. else if (this._bone1.children[0]) {
  57515. mesh.computeWorldMatrix(true);
  57516. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  57517. var pos2 = this._bone2.getAbsolutePosition(mesh);
  57518. var pos3 = this._bone1.getAbsolutePosition(mesh);
  57519. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  57520. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  57521. }
  57522. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  57523. this.maxAngle = Math.PI;
  57524. if (options) {
  57525. if (options.targetMesh) {
  57526. this.targetMesh = options.targetMesh;
  57527. this.targetMesh.computeWorldMatrix(true);
  57528. }
  57529. if (options.poleTargetMesh) {
  57530. this.poleTargetMesh = options.poleTargetMesh;
  57531. this.poleTargetMesh.computeWorldMatrix(true);
  57532. }
  57533. else if (options.poleTargetBone) {
  57534. this.poleTargetBone = options.poleTargetBone;
  57535. }
  57536. else if (this._bone1.getParent()) {
  57537. this.poleTargetBone = this._bone1.getParent();
  57538. }
  57539. if (options.poleTargetLocalOffset) {
  57540. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  57541. }
  57542. if (options.poleAngle) {
  57543. this.poleAngle = options.poleAngle;
  57544. }
  57545. if (options.bendAxis) {
  57546. this._bendAxis.copyFrom(options.bendAxis);
  57547. }
  57548. if (options.maxAngle) {
  57549. this.maxAngle = options.maxAngle;
  57550. }
  57551. if (options.slerpAmount) {
  57552. this.slerpAmount = options.slerpAmount;
  57553. }
  57554. }
  57555. }
  57556. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  57557. get: function () {
  57558. return this._maxAngle;
  57559. },
  57560. set: function (value) {
  57561. this._setMaxAngle(value);
  57562. },
  57563. enumerable: true,
  57564. configurable: true
  57565. });
  57566. BoneIKController.prototype._setMaxAngle = function (ang) {
  57567. if (ang < 0) {
  57568. ang = 0;
  57569. }
  57570. if (ang > Math.PI || ang == undefined) {
  57571. ang = Math.PI;
  57572. }
  57573. this._maxAngle = ang;
  57574. var a = this._bone1Length;
  57575. var b = this._bone2Length;
  57576. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  57577. };
  57578. BoneIKController.prototype.update = function () {
  57579. var bone1 = this._bone1;
  57580. var target = this.targetPosition;
  57581. var poleTarget = this.poleTargetPosition;
  57582. var mat1 = BoneIKController._tmpMats[0];
  57583. var mat2 = BoneIKController._tmpMats[1];
  57584. if (this.targetMesh) {
  57585. target.copyFrom(this.targetMesh.getAbsolutePosition());
  57586. }
  57587. if (this.poleTargetBone) {
  57588. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  57589. }
  57590. else if (this.poleTargetMesh) {
  57591. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  57592. }
  57593. var bonePos = BoneIKController._tmpVecs[0];
  57594. var zaxis = BoneIKController._tmpVecs[1];
  57595. var xaxis = BoneIKController._tmpVecs[2];
  57596. var yaxis = BoneIKController._tmpVecs[3];
  57597. var upAxis = BoneIKController._tmpVecs[4];
  57598. var _tmpQuat = BoneIKController._tmpQuat;
  57599. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  57600. poleTarget.subtractToRef(bonePos, upAxis);
  57601. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  57602. upAxis.y = 1;
  57603. }
  57604. else {
  57605. upAxis.normalize();
  57606. }
  57607. target.subtractToRef(bonePos, yaxis);
  57608. yaxis.normalize();
  57609. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  57610. zaxis.normalize();
  57611. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  57612. xaxis.normalize();
  57613. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  57614. var a = this._bone1Length;
  57615. var b = this._bone2Length;
  57616. var c = BABYLON.Vector3.Distance(bonePos, target);
  57617. if (this._maxReach > 0) {
  57618. c = Math.min(this._maxReach, c);
  57619. }
  57620. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  57621. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  57622. if (acosa > 1) {
  57623. acosa = 1;
  57624. }
  57625. if (acosb > 1) {
  57626. acosb = 1;
  57627. }
  57628. if (acosa < -1) {
  57629. acosa = -1;
  57630. }
  57631. if (acosb < -1) {
  57632. acosb = -1;
  57633. }
  57634. var angA = Math.acos(acosa);
  57635. var angB = Math.acos(acosb);
  57636. var angC = -angA - angB;
  57637. if (this._rightHandedSystem) {
  57638. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  57639. mat2.multiplyToRef(mat1, mat1);
  57640. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  57641. mat2.multiplyToRef(mat1, mat1);
  57642. }
  57643. else {
  57644. var _tmpVec = BoneIKController._tmpVecs[5];
  57645. _tmpVec.copyFrom(this._bendAxis);
  57646. _tmpVec.x *= -1;
  57647. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  57648. mat2.multiplyToRef(mat1, mat1);
  57649. }
  57650. if (this.poleAngle) {
  57651. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  57652. mat1.multiplyToRef(mat2, mat1);
  57653. }
  57654. if (this.slerpAmount < 1) {
  57655. if (!this._slerping) {
  57656. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  57657. }
  57658. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  57659. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  57660. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  57661. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  57662. this._slerping = true;
  57663. }
  57664. else {
  57665. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  57666. this._bone1Mat.copyFrom(mat1);
  57667. this._slerping = false;
  57668. }
  57669. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  57670. this._bone2Ang = angC;
  57671. };
  57672. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57673. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  57674. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57675. return BoneIKController;
  57676. }());
  57677. BABYLON.BoneIKController = BoneIKController;
  57678. })(BABYLON || (BABYLON = {}));
  57679. //# sourceMappingURL=babylon.boneIKController.js.map
  57680. var BABYLON;
  57681. (function (BABYLON) {
  57682. var BoneLookController = (function () {
  57683. /**
  57684. * Create a BoneLookController
  57685. * @param mesh the mesh that the bone belongs to
  57686. * @param bone the bone that will be looking to the target
  57687. * @param target the target Vector3 to look at
  57688. * @param settings optional settings:
  57689. * - maxYaw: the maximum angle the bone will yaw to
  57690. * - minYaw: the minimum angle the bone will yaw to
  57691. * - maxPitch: the maximum angle the bone will pitch to
  57692. * - minPitch: the minimum angle the bone will yaw to
  57693. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  57694. * - upAxis: the up axis of the coordinate system
  57695. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  57696. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  57697. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  57698. * - adjustYaw: used to make an adjustment to the yaw of the bone
  57699. * - adjustPitch: used to make an adjustment to the pitch of the bone
  57700. * - adjustRoll: used to make an adjustment to the roll of the bone
  57701. **/
  57702. function BoneLookController(mesh, bone, target, options) {
  57703. /**
  57704. * The up axis of the coordinate system that is used when the bone is rotated.
  57705. */
  57706. this.upAxis = BABYLON.Vector3.Up();
  57707. /**
  57708. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  57709. */
  57710. this.upAxisSpace = BABYLON.Space.LOCAL;
  57711. /**
  57712. * Used to make an adjustment to the yaw of the bone.
  57713. */
  57714. this.adjustYaw = 0;
  57715. /**
  57716. * Used to make an adjustment to the pitch of the bone.
  57717. */
  57718. this.adjustPitch = 0;
  57719. /**
  57720. * Used to make an adjustment to the roll of the bone.
  57721. */
  57722. this.adjustRoll = 0;
  57723. /**
  57724. * 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).
  57725. */
  57726. this.slerpAmount = 1;
  57727. this._boneQuat = BABYLON.Quaternion.Identity();
  57728. this._slerping = false;
  57729. this._firstFrameSkipped = false;
  57730. this._fowardAxis = BABYLON.Vector3.Forward();
  57731. this.mesh = mesh;
  57732. this.bone = bone;
  57733. this.target = target;
  57734. if (options) {
  57735. if (options.adjustYaw) {
  57736. this.adjustYaw = options.adjustYaw;
  57737. }
  57738. if (options.adjustPitch) {
  57739. this.adjustPitch = options.adjustPitch;
  57740. }
  57741. if (options.adjustRoll) {
  57742. this.adjustRoll = options.adjustRoll;
  57743. }
  57744. if (options.maxYaw != null) {
  57745. this.maxYaw = options.maxYaw;
  57746. }
  57747. else {
  57748. this.maxYaw = Math.PI;
  57749. }
  57750. if (options.minYaw != null) {
  57751. this.minYaw = options.minYaw;
  57752. }
  57753. else {
  57754. this.minYaw = -Math.PI;
  57755. }
  57756. if (options.maxPitch != null) {
  57757. this.maxPitch = options.maxPitch;
  57758. }
  57759. else {
  57760. this.maxPitch = Math.PI;
  57761. }
  57762. if (options.minPitch != null) {
  57763. this.minPitch = options.minPitch;
  57764. }
  57765. else {
  57766. this.minPitch = -Math.PI;
  57767. }
  57768. if (options.slerpAmount != null) {
  57769. this.slerpAmount = options.slerpAmount;
  57770. }
  57771. if (options.upAxis != null) {
  57772. this.upAxis = options.upAxis;
  57773. }
  57774. if (options.upAxisSpace != null) {
  57775. this.upAxisSpace = options.upAxisSpace;
  57776. }
  57777. if (options.yawAxis != null || options.pitchAxis != null) {
  57778. var newYawAxis = BABYLON.Axis.Y;
  57779. var newPitchAxis = BABYLON.Axis.X;
  57780. if (options.yawAxis != null) {
  57781. newYawAxis = options.yawAxis.clone();
  57782. newYawAxis.normalize();
  57783. }
  57784. if (options.pitchAxis != null) {
  57785. newPitchAxis = options.pitchAxis.clone();
  57786. newPitchAxis.normalize();
  57787. }
  57788. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  57789. this._transformYawPitch = BABYLON.Matrix.Identity();
  57790. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  57791. this._transformYawPitchInv = this._transformYawPitch.clone();
  57792. this._transformYawPitch.invert();
  57793. }
  57794. }
  57795. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  57796. this.upAxisSpace = BABYLON.Space.LOCAL;
  57797. }
  57798. }
  57799. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  57800. /**
  57801. * Get/set the minimum yaw angle that the bone can look to.
  57802. */
  57803. get: function () {
  57804. return this._minYaw;
  57805. },
  57806. set: function (value) {
  57807. this._minYaw = value;
  57808. this._minYawSin = Math.sin(value);
  57809. this._minYawCos = Math.cos(value);
  57810. if (this._maxYaw != null) {
  57811. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  57812. this._yawRange = this._maxYaw - this._minYaw;
  57813. }
  57814. },
  57815. enumerable: true,
  57816. configurable: true
  57817. });
  57818. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  57819. /**
  57820. * Get/set the maximum yaw angle that the bone can look to.
  57821. */
  57822. get: function () {
  57823. return this._maxYaw;
  57824. },
  57825. set: function (value) {
  57826. this._maxYaw = value;
  57827. this._maxYawSin = Math.sin(value);
  57828. this._maxYawCos = Math.cos(value);
  57829. if (this._minYaw != null) {
  57830. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  57831. this._yawRange = this._maxYaw - this._minYaw;
  57832. }
  57833. },
  57834. enumerable: true,
  57835. configurable: true
  57836. });
  57837. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  57838. /**
  57839. * Get/set the minimum pitch angle that the bone can look to.
  57840. */
  57841. get: function () {
  57842. return this._minPitch;
  57843. },
  57844. set: function (value) {
  57845. this._minPitch = value;
  57846. this._minPitchTan = Math.tan(value);
  57847. },
  57848. enumerable: true,
  57849. configurable: true
  57850. });
  57851. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  57852. /**
  57853. * Get/set the maximum pitch angle that the bone can look to.
  57854. */
  57855. get: function () {
  57856. return this._maxPitch;
  57857. },
  57858. set: function (value) {
  57859. this._maxPitch = value;
  57860. this._maxPitchTan = Math.tan(value);
  57861. },
  57862. enumerable: true,
  57863. configurable: true
  57864. });
  57865. /**
  57866. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  57867. */
  57868. BoneLookController.prototype.update = function () {
  57869. //skip the first frame when slerping so that the mesh rotation is correct
  57870. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  57871. this._firstFrameSkipped = true;
  57872. return;
  57873. }
  57874. var bone = this.bone;
  57875. var bonePos = BoneLookController._tmpVecs[0];
  57876. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  57877. var target = this.target;
  57878. var _tmpMat1 = BoneLookController._tmpMats[0];
  57879. var _tmpMat2 = BoneLookController._tmpMats[1];
  57880. var mesh = this.mesh;
  57881. var parentBone = bone.getParent();
  57882. var upAxis = BoneLookController._tmpVecs[1];
  57883. upAxis.copyFrom(this.upAxis);
  57884. if (this.upAxisSpace == BABYLON.Space.BONE) {
  57885. if (this._transformYawPitch) {
  57886. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  57887. }
  57888. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  57889. }
  57890. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  57891. mesh.getDirectionToRef(upAxis, upAxis);
  57892. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  57893. upAxis.normalize();
  57894. }
  57895. }
  57896. var checkYaw = false;
  57897. var checkPitch = false;
  57898. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  57899. checkYaw = true;
  57900. }
  57901. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  57902. checkPitch = true;
  57903. }
  57904. if (checkYaw || checkPitch) {
  57905. var spaceMat = BoneLookController._tmpMats[2];
  57906. var spaceMatInv = BoneLookController._tmpMats[3];
  57907. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  57908. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  57909. }
  57910. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  57911. spaceMat.copyFrom(mesh.getWorldMatrix());
  57912. }
  57913. else {
  57914. var forwardAxis = BoneLookController._tmpVecs[2];
  57915. forwardAxis.copyFrom(this._fowardAxis);
  57916. if (this._transformYawPitch) {
  57917. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  57918. }
  57919. if (parentBone) {
  57920. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  57921. }
  57922. else {
  57923. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  57924. }
  57925. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  57926. rightAxis.normalize();
  57927. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  57928. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  57929. }
  57930. spaceMat.invertToRef(spaceMatInv);
  57931. var xzlen;
  57932. if (checkPitch) {
  57933. var localTarget = BoneLookController._tmpVecs[3];
  57934. target.subtractToRef(bonePos, localTarget);
  57935. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  57936. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57937. var pitch = Math.atan2(localTarget.y, xzlen);
  57938. var newPitch = pitch;
  57939. if (pitch > this._maxPitch) {
  57940. localTarget.y = this._maxPitchTan * xzlen;
  57941. newPitch = this._maxPitch;
  57942. }
  57943. else if (pitch < this._minPitch) {
  57944. localTarget.y = this._minPitchTan * xzlen;
  57945. newPitch = this._minPitch;
  57946. }
  57947. if (pitch != newPitch) {
  57948. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  57949. localTarget.addInPlace(bonePos);
  57950. target = localTarget;
  57951. }
  57952. }
  57953. if (checkYaw) {
  57954. var localTarget = BoneLookController._tmpVecs[4];
  57955. target.subtractToRef(bonePos, localTarget);
  57956. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  57957. var yaw = Math.atan2(localTarget.x, localTarget.z);
  57958. var newYaw = yaw;
  57959. if (yaw > this._maxYaw || yaw < this._minYaw) {
  57960. if (xzlen == null) {
  57961. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57962. }
  57963. if (this._yawRange > Math.PI) {
  57964. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  57965. localTarget.z = this._maxYawCos * xzlen;
  57966. localTarget.x = this._maxYawSin * xzlen;
  57967. newYaw = this._maxYaw;
  57968. }
  57969. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  57970. localTarget.z = this._minYawCos * xzlen;
  57971. localTarget.x = this._minYawSin * xzlen;
  57972. newYaw = this._minYaw;
  57973. }
  57974. }
  57975. else {
  57976. if (yaw > this._maxYaw) {
  57977. localTarget.z = this._maxYawCos * xzlen;
  57978. localTarget.x = this._maxYawSin * xzlen;
  57979. newYaw = this._maxYaw;
  57980. }
  57981. else if (yaw < this._minYaw) {
  57982. localTarget.z = this._minYawCos * xzlen;
  57983. localTarget.x = this._minYawSin * xzlen;
  57984. newYaw = this._minYaw;
  57985. }
  57986. }
  57987. }
  57988. if (this._slerping && this._yawRange > Math.PI) {
  57989. //are we going to be crossing into the min/max region?
  57990. var boneFwd = BoneLookController._tmpVecs[8];
  57991. boneFwd.copyFrom(BABYLON.Axis.Z);
  57992. if (this._transformYawPitch) {
  57993. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  57994. }
  57995. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  57996. this._boneQuat.toRotationMatrix(boneRotMat);
  57997. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  57998. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  57999. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  58000. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  58001. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  58002. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  58003. if (angBtwTar > angBtwMidYaw) {
  58004. if (xzlen == null) {
  58005. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  58006. }
  58007. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  58008. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  58009. if (angBtwMin < angBtwMax) {
  58010. newYaw = boneYaw + Math.PI * .75;
  58011. localTarget.z = Math.cos(newYaw) * xzlen;
  58012. localTarget.x = Math.sin(newYaw) * xzlen;
  58013. }
  58014. else {
  58015. newYaw = boneYaw - Math.PI * .75;
  58016. localTarget.z = Math.cos(newYaw) * xzlen;
  58017. localTarget.x = Math.sin(newYaw) * xzlen;
  58018. }
  58019. }
  58020. }
  58021. if (yaw != newYaw) {
  58022. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  58023. localTarget.addInPlace(bonePos);
  58024. target = localTarget;
  58025. }
  58026. }
  58027. }
  58028. var zaxis = BoneLookController._tmpVecs[5];
  58029. var xaxis = BoneLookController._tmpVecs[6];
  58030. var yaxis = BoneLookController._tmpVecs[7];
  58031. var _tmpQuat = BoneLookController._tmpQuat;
  58032. target.subtractToRef(bonePos, zaxis);
  58033. zaxis.normalize();
  58034. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  58035. xaxis.normalize();
  58036. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  58037. yaxis.normalize();
  58038. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  58039. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  58040. return;
  58041. }
  58042. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  58043. return;
  58044. }
  58045. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  58046. return;
  58047. }
  58048. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  58049. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  58050. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  58051. }
  58052. if (this.slerpAmount < 1) {
  58053. if (!this._slerping) {
  58054. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  58055. }
  58056. if (this._transformYawPitch) {
  58057. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  58058. }
  58059. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  58060. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  58061. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  58062. this._slerping = true;
  58063. }
  58064. else {
  58065. if (this._transformYawPitch) {
  58066. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  58067. }
  58068. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  58069. this._slerping = false;
  58070. }
  58071. };
  58072. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  58073. var angDiff = ang2 - ang1;
  58074. angDiff %= Math.PI * 2;
  58075. if (angDiff > Math.PI) {
  58076. angDiff -= Math.PI * 2;
  58077. }
  58078. else if (angDiff < -Math.PI) {
  58079. angDiff += Math.PI * 2;
  58080. }
  58081. return angDiff;
  58082. };
  58083. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  58084. ang1 %= (2 * Math.PI);
  58085. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  58086. ang2 %= (2 * Math.PI);
  58087. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  58088. var ab = 0;
  58089. if (ang1 < ang2) {
  58090. ab = ang2 - ang1;
  58091. }
  58092. else {
  58093. ab = ang1 - ang2;
  58094. }
  58095. if (ab > Math.PI) {
  58096. ab = Math.PI * 2 - ab;
  58097. }
  58098. return ab;
  58099. };
  58100. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  58101. ang %= (2 * Math.PI);
  58102. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  58103. ang1 %= (2 * Math.PI);
  58104. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  58105. ang2 %= (2 * Math.PI);
  58106. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  58107. if (ang1 < ang2) {
  58108. if (ang > ang1 && ang < ang2) {
  58109. return true;
  58110. }
  58111. }
  58112. else {
  58113. if (ang > ang2 && ang < ang1) {
  58114. return true;
  58115. }
  58116. }
  58117. return false;
  58118. };
  58119. 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()];
  58120. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  58121. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  58122. return BoneLookController;
  58123. }());
  58124. BABYLON.BoneLookController = BoneLookController;
  58125. })(BABYLON || (BABYLON = {}));
  58126. //# sourceMappingURL=babylon.boneLookController.js.map
  58127. var BABYLON;
  58128. (function (BABYLON) {
  58129. var Skeleton = (function () {
  58130. function Skeleton(name, id, scene) {
  58131. this.name = name;
  58132. this.id = id;
  58133. this.bones = new Array();
  58134. this.needInitialSkinMatrix = false;
  58135. this._isDirty = true;
  58136. this._meshesWithPoseMatrix = new Array();
  58137. this._identity = BABYLON.Matrix.Identity();
  58138. this._ranges = {};
  58139. this._lastAbsoluteTransformsUpdateId = -1;
  58140. // Events
  58141. /**
  58142. * An event triggered before computing the skeleton's matrices
  58143. * @type {BABYLON.Observable}
  58144. */
  58145. this.onBeforeComputeObservable = new BABYLON.Observable();
  58146. this.bones = [];
  58147. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58148. scene.skeletons.push(this);
  58149. //make sure it will recalculate the matrix next time prepare is called.
  58150. this._isDirty = true;
  58151. }
  58152. // Members
  58153. Skeleton.prototype.getTransformMatrices = function (mesh) {
  58154. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  58155. return mesh._bonesTransformMatrices;
  58156. }
  58157. if (!this._transformMatrices) {
  58158. this.prepare();
  58159. }
  58160. return this._transformMatrices;
  58161. };
  58162. Skeleton.prototype.getScene = function () {
  58163. return this._scene;
  58164. };
  58165. // Methods
  58166. /**
  58167. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  58168. */
  58169. Skeleton.prototype.toString = function (fullDetails) {
  58170. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  58171. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  58172. if (fullDetails) {
  58173. ret += ", Ranges: {";
  58174. var first = true;
  58175. for (var name_1 in this._ranges) {
  58176. if (first) {
  58177. ret += ", ";
  58178. first = false;
  58179. }
  58180. ret += name_1;
  58181. }
  58182. ret += "}";
  58183. }
  58184. return ret;
  58185. };
  58186. /**
  58187. * Get bone's index searching by name
  58188. * @param {string} name is bone's name to search for
  58189. * @return {number} Indice of the bone. Returns -1 if not found
  58190. */
  58191. Skeleton.prototype.getBoneIndexByName = function (name) {
  58192. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  58193. if (this.bones[boneIndex].name === name) {
  58194. return boneIndex;
  58195. }
  58196. }
  58197. return -1;
  58198. };
  58199. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  58200. // check name not already in use
  58201. if (!this._ranges[name]) {
  58202. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  58203. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58204. if (this.bones[i].animations[0]) {
  58205. this.bones[i].animations[0].createRange(name, from, to);
  58206. }
  58207. }
  58208. }
  58209. };
  58210. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  58211. if (deleteFrames === void 0) { deleteFrames = true; }
  58212. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58213. if (this.bones[i].animations[0]) {
  58214. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  58215. }
  58216. }
  58217. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  58218. };
  58219. Skeleton.prototype.getAnimationRange = function (name) {
  58220. return this._ranges[name];
  58221. };
  58222. /**
  58223. * Returns as an Array, all AnimationRanges defined on this skeleton
  58224. */
  58225. Skeleton.prototype.getAnimationRanges = function () {
  58226. var animationRanges = [];
  58227. var name;
  58228. var i = 0;
  58229. for (name in this._ranges) {
  58230. animationRanges[i] = this._ranges[name];
  58231. i++;
  58232. }
  58233. return animationRanges;
  58234. };
  58235. /**
  58236. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  58237. */
  58238. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  58239. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  58240. if (this._ranges[name] || !source.getAnimationRange(name)) {
  58241. return false;
  58242. }
  58243. var ret = true;
  58244. var frameOffset = this._getHighestAnimationFrame() + 1;
  58245. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  58246. var boneDict = {};
  58247. var sourceBones = source.bones;
  58248. var nBones;
  58249. var i;
  58250. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  58251. boneDict[sourceBones[i].name] = sourceBones[i];
  58252. }
  58253. if (this.bones.length !== sourceBones.length) {
  58254. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  58255. ret = false;
  58256. }
  58257. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  58258. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  58259. var boneName = this.bones[i].name;
  58260. var sourceBone = boneDict[boneName];
  58261. if (sourceBone) {
  58262. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  58263. }
  58264. else {
  58265. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  58266. ret = false;
  58267. }
  58268. }
  58269. // do not call createAnimationRange(), since it also is done to bones, which was already done
  58270. var range = source.getAnimationRange(name);
  58271. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  58272. return ret;
  58273. };
  58274. Skeleton.prototype.returnToRest = function () {
  58275. for (var index = 0; index < this.bones.length; index++) {
  58276. this.bones[index].returnToRest();
  58277. }
  58278. };
  58279. Skeleton.prototype._getHighestAnimationFrame = function () {
  58280. var ret = 0;
  58281. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58282. if (this.bones[i].animations[0]) {
  58283. var highest = this.bones[i].animations[0].getHighestFrame();
  58284. if (ret < highest) {
  58285. ret = highest;
  58286. }
  58287. }
  58288. }
  58289. return ret;
  58290. };
  58291. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  58292. var range = this.getAnimationRange(name);
  58293. if (!range) {
  58294. return null;
  58295. }
  58296. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  58297. };
  58298. Skeleton.prototype._markAsDirty = function () {
  58299. this._isDirty = true;
  58300. };
  58301. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  58302. this._meshesWithPoseMatrix.push(mesh);
  58303. };
  58304. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  58305. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  58306. if (index > -1) {
  58307. this._meshesWithPoseMatrix.splice(index, 1);
  58308. }
  58309. };
  58310. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  58311. this.onBeforeComputeObservable.notifyObservers(this);
  58312. for (var index = 0; index < this.bones.length; index++) {
  58313. var bone = this.bones[index];
  58314. var parentBone = bone.getParent();
  58315. if (parentBone) {
  58316. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  58317. }
  58318. else {
  58319. if (initialSkinMatrix) {
  58320. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  58321. }
  58322. else {
  58323. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  58324. }
  58325. }
  58326. if (bone._index !== -1) {
  58327. var mappedIndex = bone._index === undefined ? index : bone._index;
  58328. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  58329. }
  58330. }
  58331. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  58332. };
  58333. Skeleton.prototype.prepare = function () {
  58334. if (!this._isDirty) {
  58335. return;
  58336. }
  58337. if (this.needInitialSkinMatrix) {
  58338. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  58339. var mesh = this._meshesWithPoseMatrix[index];
  58340. var poseMatrix = mesh.getPoseMatrix();
  58341. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  58342. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  58343. }
  58344. if (this._synchronizedWithMesh !== mesh) {
  58345. this._synchronizedWithMesh = mesh;
  58346. // Prepare bones
  58347. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  58348. var bone = this.bones[boneIndex];
  58349. if (!bone.getParent()) {
  58350. var matrix = bone.getBaseMatrix();
  58351. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  58352. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  58353. }
  58354. }
  58355. }
  58356. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  58357. }
  58358. }
  58359. else {
  58360. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  58361. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  58362. }
  58363. this._computeTransformMatrices(this._transformMatrices, null);
  58364. }
  58365. this._isDirty = false;
  58366. this._scene._activeBones.addCount(this.bones.length, false);
  58367. };
  58368. Skeleton.prototype.getAnimatables = function () {
  58369. if (!this._animatables || this._animatables.length !== this.bones.length) {
  58370. this._animatables = [];
  58371. for (var index = 0; index < this.bones.length; index++) {
  58372. this._animatables.push(this.bones[index]);
  58373. }
  58374. }
  58375. return this._animatables;
  58376. };
  58377. Skeleton.prototype.clone = function (name, id) {
  58378. var result = new Skeleton(name, id || name, this._scene);
  58379. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  58380. for (var index = 0; index < this.bones.length; index++) {
  58381. var source = this.bones[index];
  58382. var parentBone = null;
  58383. if (source.getParent()) {
  58384. var parentIndex = this.bones.indexOf(source.getParent());
  58385. parentBone = result.bones[parentIndex];
  58386. }
  58387. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  58388. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  58389. }
  58390. if (this._ranges) {
  58391. result._ranges = {};
  58392. for (var rangeName in this._ranges) {
  58393. result._ranges[rangeName] = this._ranges[rangeName].clone();
  58394. }
  58395. }
  58396. this._isDirty = true;
  58397. return result;
  58398. };
  58399. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  58400. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  58401. this.bones.forEach(function (bone) {
  58402. bone.animations.forEach(function (animation) {
  58403. animation.enableBlending = true;
  58404. animation.blendingSpeed = blendingSpeed;
  58405. });
  58406. });
  58407. };
  58408. Skeleton.prototype.dispose = function () {
  58409. this._meshesWithPoseMatrix = [];
  58410. // Animations
  58411. this.getScene().stopAnimation(this);
  58412. // Remove from scene
  58413. this.getScene().removeSkeleton(this);
  58414. };
  58415. Skeleton.prototype.serialize = function () {
  58416. var serializationObject = {};
  58417. serializationObject.name = this.name;
  58418. serializationObject.id = this.id;
  58419. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  58420. serializationObject.bones = [];
  58421. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  58422. for (var index = 0; index < this.bones.length; index++) {
  58423. var bone = this.bones[index];
  58424. var serializedBone = {
  58425. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  58426. name: bone.name,
  58427. matrix: bone.getBaseMatrix().toArray(),
  58428. rest: bone.getRestPose().toArray()
  58429. };
  58430. serializationObject.bones.push(serializedBone);
  58431. if (bone.length) {
  58432. serializedBone.length = bone.length;
  58433. }
  58434. if (bone.animations && bone.animations.length > 0) {
  58435. serializedBone.animation = bone.animations[0].serialize();
  58436. }
  58437. serializationObject.ranges = [];
  58438. for (var name in this._ranges) {
  58439. var range = {};
  58440. range.name = name;
  58441. range.from = this._ranges[name].from;
  58442. range.to = this._ranges[name].to;
  58443. serializationObject.ranges.push(range);
  58444. }
  58445. }
  58446. return serializationObject;
  58447. };
  58448. Skeleton.Parse = function (parsedSkeleton, scene) {
  58449. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  58450. if (parsedSkeleton.dimensionsAtRest) {
  58451. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  58452. }
  58453. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  58454. var index;
  58455. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  58456. var parsedBone = parsedSkeleton.bones[index];
  58457. var parentBone = null;
  58458. if (parsedBone.parentBoneIndex > -1) {
  58459. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  58460. }
  58461. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  58462. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  58463. if (parsedBone.length) {
  58464. bone.length = parsedBone.length;
  58465. }
  58466. if (parsedBone.animation) {
  58467. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  58468. }
  58469. }
  58470. // placed after bones, so createAnimationRange can cascade down
  58471. if (parsedSkeleton.ranges) {
  58472. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  58473. var data = parsedSkeleton.ranges[index];
  58474. skeleton.createAnimationRange(data.name, data.from, data.to);
  58475. }
  58476. }
  58477. return skeleton;
  58478. };
  58479. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  58480. if (forceUpdate === void 0) { forceUpdate = false; }
  58481. var renderId = this._scene.getRenderId();
  58482. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  58483. this.bones[0].computeAbsoluteTransforms();
  58484. this._lastAbsoluteTransformsUpdateId = renderId;
  58485. }
  58486. };
  58487. Skeleton.prototype.getPoseMatrix = function () {
  58488. var poseMatrix;
  58489. if (this._meshesWithPoseMatrix.length > 0) {
  58490. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  58491. }
  58492. return poseMatrix;
  58493. };
  58494. Skeleton.prototype.sortBones = function () {
  58495. var bones = new Array();
  58496. var visited = new Array(this.bones.length);
  58497. for (var index = 0; index < this.bones.length; index++) {
  58498. this._sortBones(index, bones, visited);
  58499. }
  58500. this.bones = bones;
  58501. };
  58502. Skeleton.prototype._sortBones = function (index, bones, visited) {
  58503. if (visited[index]) {
  58504. return;
  58505. }
  58506. visited[index] = true;
  58507. var bone = this.bones[index];
  58508. if (bone._index === undefined) {
  58509. bone._index = index;
  58510. }
  58511. var parentBone = bone.getParent();
  58512. if (parentBone) {
  58513. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  58514. }
  58515. bones.push(bone);
  58516. };
  58517. return Skeleton;
  58518. }());
  58519. BABYLON.Skeleton = Skeleton;
  58520. })(BABYLON || (BABYLON = {}));
  58521. //# sourceMappingURL=babylon.skeleton.js.map
  58522. var BABYLON;
  58523. (function (BABYLON) {
  58524. var SphericalPolynomial = (function () {
  58525. function SphericalPolynomial() {
  58526. this.x = BABYLON.Vector3.Zero();
  58527. this.y = BABYLON.Vector3.Zero();
  58528. this.z = BABYLON.Vector3.Zero();
  58529. this.xx = BABYLON.Vector3.Zero();
  58530. this.yy = BABYLON.Vector3.Zero();
  58531. this.zz = BABYLON.Vector3.Zero();
  58532. this.xy = BABYLON.Vector3.Zero();
  58533. this.yz = BABYLON.Vector3.Zero();
  58534. this.zx = BABYLON.Vector3.Zero();
  58535. }
  58536. SphericalPolynomial.prototype.addAmbient = function (color) {
  58537. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  58538. this.xx = this.xx.add(colorVector);
  58539. this.yy = this.yy.add(colorVector);
  58540. this.zz = this.zz.add(colorVector);
  58541. };
  58542. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  58543. var result = new SphericalPolynomial();
  58544. result.x = harmonics.L11.scale(1.02333);
  58545. result.y = harmonics.L1_1.scale(1.02333);
  58546. result.z = harmonics.L10.scale(1.02333);
  58547. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  58548. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  58549. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  58550. result.yz = harmonics.L2_1.scale(0.858086);
  58551. result.zx = harmonics.L21.scale(0.858086);
  58552. result.xy = harmonics.L2_2.scale(0.858086);
  58553. result.scale(1.0 / Math.PI);
  58554. return result;
  58555. };
  58556. SphericalPolynomial.prototype.scale = function (scale) {
  58557. this.x = this.x.scale(scale);
  58558. this.y = this.y.scale(scale);
  58559. this.z = this.z.scale(scale);
  58560. this.xx = this.xx.scale(scale);
  58561. this.yy = this.yy.scale(scale);
  58562. this.zz = this.zz.scale(scale);
  58563. this.yz = this.yz.scale(scale);
  58564. this.zx = this.zx.scale(scale);
  58565. this.xy = this.xy.scale(scale);
  58566. };
  58567. return SphericalPolynomial;
  58568. }());
  58569. BABYLON.SphericalPolynomial = SphericalPolynomial;
  58570. var SphericalHarmonics = (function () {
  58571. function SphericalHarmonics() {
  58572. this.L00 = BABYLON.Vector3.Zero();
  58573. this.L1_1 = BABYLON.Vector3.Zero();
  58574. this.L10 = BABYLON.Vector3.Zero();
  58575. this.L11 = BABYLON.Vector3.Zero();
  58576. this.L2_2 = BABYLON.Vector3.Zero();
  58577. this.L2_1 = BABYLON.Vector3.Zero();
  58578. this.L20 = BABYLON.Vector3.Zero();
  58579. this.L21 = BABYLON.Vector3.Zero();
  58580. this.L22 = BABYLON.Vector3.Zero();
  58581. }
  58582. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  58583. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  58584. var c = colorVector.scale(deltaSolidAngle);
  58585. this.L00 = this.L00.add(c.scale(0.282095));
  58586. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  58587. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  58588. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  58589. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  58590. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  58591. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  58592. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  58593. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  58594. };
  58595. SphericalHarmonics.prototype.scale = function (scale) {
  58596. this.L00 = this.L00.scale(scale);
  58597. this.L1_1 = this.L1_1.scale(scale);
  58598. this.L10 = this.L10.scale(scale);
  58599. this.L11 = this.L11.scale(scale);
  58600. this.L2_2 = this.L2_2.scale(scale);
  58601. this.L2_1 = this.L2_1.scale(scale);
  58602. this.L20 = this.L20.scale(scale);
  58603. this.L21 = this.L21.scale(scale);
  58604. this.L22 = this.L22.scale(scale);
  58605. };
  58606. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  58607. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  58608. //
  58609. // E_lm = A_l * L_lm
  58610. //
  58611. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  58612. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  58613. // the scaling factors are given in equation 9.
  58614. // Constant (Band 0)
  58615. this.L00 = this.L00.scale(3.141593);
  58616. // Linear (Band 1)
  58617. this.L1_1 = this.L1_1.scale(2.094395);
  58618. this.L10 = this.L10.scale(2.094395);
  58619. this.L11 = this.L11.scale(2.094395);
  58620. // Quadratic (Band 2)
  58621. this.L2_2 = this.L2_2.scale(0.785398);
  58622. this.L2_1 = this.L2_1.scale(0.785398);
  58623. this.L20 = this.L20.scale(0.785398);
  58624. this.L21 = this.L21.scale(0.785398);
  58625. this.L22 = this.L22.scale(0.785398);
  58626. };
  58627. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  58628. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  58629. // L = (1/pi) * E * rho
  58630. //
  58631. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  58632. this.scale(1.0 / Math.PI);
  58633. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  58634. // (The pixel shader must apply albedo after texture fetches, etc).
  58635. };
  58636. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  58637. var result = new SphericalHarmonics();
  58638. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  58639. result.L1_1 = polynomial.y.scale(0.977204);
  58640. result.L10 = polynomial.z.scale(0.977204);
  58641. result.L11 = polynomial.x.scale(0.977204);
  58642. result.L2_2 = polynomial.xy.scale(1.16538);
  58643. result.L2_1 = polynomial.yz.scale(1.16538);
  58644. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  58645. result.L21 = polynomial.zx.scale(1.16538);
  58646. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  58647. result.scale(Math.PI);
  58648. return result;
  58649. };
  58650. return SphericalHarmonics;
  58651. }());
  58652. BABYLON.SphericalHarmonics = SphericalHarmonics;
  58653. })(BABYLON || (BABYLON = {}));
  58654. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  58655. var BABYLON;
  58656. (function (BABYLON) {
  58657. var Internals;
  58658. (function (Internals) {
  58659. var FileFaceOrientation = (function () {
  58660. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  58661. this.name = name;
  58662. this.worldAxisForNormal = worldAxisForNormal;
  58663. this.worldAxisForFileX = worldAxisForFileX;
  58664. this.worldAxisForFileY = worldAxisForFileY;
  58665. }
  58666. return FileFaceOrientation;
  58667. }());
  58668. ;
  58669. /**
  58670. * Helper class dealing with the extraction of spherical polynomial dataArray
  58671. * from a cube map.
  58672. */
  58673. var CubeMapToSphericalPolynomialTools = (function () {
  58674. function CubeMapToSphericalPolynomialTools() {
  58675. }
  58676. /**
  58677. * Converts a texture to the according Spherical Polynomial data.
  58678. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58679. *
  58680. * @param texture The texture to extract the information from.
  58681. * @return The Spherical Polynomial data.
  58682. */
  58683. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  58684. if (!texture.isCube) {
  58685. // Only supports cube Textures currently.
  58686. return null;
  58687. }
  58688. var size = texture.getSize().width;
  58689. var right = texture.readPixels(0);
  58690. var left = texture.readPixels(1);
  58691. var up;
  58692. var down;
  58693. if (texture.isRenderTarget) {
  58694. up = texture.readPixels(3);
  58695. down = texture.readPixels(2);
  58696. }
  58697. else {
  58698. up = texture.readPixels(2);
  58699. down = texture.readPixels(3);
  58700. }
  58701. var front = texture.readPixels(4);
  58702. var back = texture.readPixels(5);
  58703. var gammaSpace = texture.gammaSpace;
  58704. // Always read as RGBA.
  58705. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  58706. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58707. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58708. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58709. }
  58710. var cubeInfo = {
  58711. size: size,
  58712. right: right,
  58713. left: left,
  58714. up: up,
  58715. down: down,
  58716. front: front,
  58717. back: back,
  58718. format: format,
  58719. type: type,
  58720. gammaSpace: gammaSpace,
  58721. };
  58722. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  58723. };
  58724. /**
  58725. * Converts a cubemap to the according Spherical Polynomial data.
  58726. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58727. *
  58728. * @param cubeInfo The Cube map to extract the information from.
  58729. * @return The Spherical Polynomial data.
  58730. */
  58731. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  58732. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  58733. var totalSolidAngle = 0.0;
  58734. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  58735. var du = 2.0 / cubeInfo.size;
  58736. var dv = du;
  58737. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  58738. var minUV = du * 0.5 - 1.0;
  58739. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58740. var fileFace = this.FileFaces[faceIndex];
  58741. var dataArray = cubeInfo[fileFace.name];
  58742. var v = minUV;
  58743. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  58744. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  58745. // Because SP is still linear, so summation is fine in that basis.
  58746. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  58747. for (var y = 0; y < cubeInfo.size; y++) {
  58748. var u = minUV;
  58749. for (var x = 0; x < cubeInfo.size; x++) {
  58750. // World direction (not normalised)
  58751. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  58752. worldDirection.normalize();
  58753. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  58754. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  58755. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  58756. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  58757. // Handle Integer types.
  58758. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58759. r /= 255;
  58760. g /= 255;
  58761. b /= 255;
  58762. }
  58763. // Handle Gamma space textures.
  58764. if (cubeInfo.gammaSpace) {
  58765. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  58766. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  58767. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  58768. }
  58769. var color = new BABYLON.Color3(r, g, b);
  58770. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58771. totalSolidAngle += deltaSolidAngle;
  58772. u += du;
  58773. }
  58774. v += dv;
  58775. }
  58776. }
  58777. // Solid angle for entire sphere is 4*pi
  58778. var sphereSolidAngle = 4.0 * Math.PI;
  58779. // Adjust the solid angle to allow for how many faces we processed.
  58780. var facesProcessed = 6.0;
  58781. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  58782. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  58783. // This is needed because the numerical integration over the cube uses a
  58784. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  58785. // and also to compensate for accumulative error due to float precision in the summation.
  58786. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  58787. sphericalHarmonics.scale(correctionFactor);
  58788. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  58789. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  58790. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  58791. };
  58792. CubeMapToSphericalPolynomialTools.FileFaces = [
  58793. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  58794. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  58795. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  58796. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  58797. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  58798. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  58799. ];
  58800. return CubeMapToSphericalPolynomialTools;
  58801. }());
  58802. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  58803. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58804. })(BABYLON || (BABYLON = {}));
  58805. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  58806. var BABYLON;
  58807. (function (BABYLON) {
  58808. var Internals;
  58809. (function (Internals) {
  58810. /**
  58811. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  58812. */
  58813. var PanoramaToCubeMapTools = (function () {
  58814. function PanoramaToCubeMapTools() {
  58815. }
  58816. /**
  58817. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  58818. *
  58819. * @param float32Array The source data.
  58820. * @param inputWidth The width of the input panorama.
  58821. * @param inputhHeight The height of the input panorama.
  58822. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  58823. * @return The cubemap data
  58824. */
  58825. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  58826. if (!float32Array) {
  58827. throw "ConvertPanoramaToCubemap: input cannot be null";
  58828. }
  58829. if (float32Array.length != inputWidth * inputHeight * 3) {
  58830. throw "ConvertPanoramaToCubemap: input size is wrong";
  58831. }
  58832. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  58833. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  58834. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  58835. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  58836. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  58837. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  58838. return {
  58839. front: textureFront,
  58840. back: textureBack,
  58841. left: textureLeft,
  58842. right: textureRight,
  58843. up: textureUp,
  58844. down: textureDown,
  58845. size: size,
  58846. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  58847. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  58848. gammaSpace: false,
  58849. };
  58850. };
  58851. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  58852. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  58853. var textureArray = new Float32Array(buffer);
  58854. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  58855. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  58856. var dy = 1 / texSize;
  58857. var fy = 0;
  58858. for (var y = 0; y < texSize; y++) {
  58859. var xv1 = faceData[0];
  58860. var xv2 = faceData[2];
  58861. for (var x = 0; x < texSize; x++) {
  58862. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  58863. v.normalize();
  58864. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  58865. // 3 channels per pixels
  58866. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  58867. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  58868. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  58869. xv1 = xv1.add(rotDX1);
  58870. xv2 = xv2.add(rotDX2);
  58871. }
  58872. fy += dy;
  58873. }
  58874. return textureArray;
  58875. };
  58876. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  58877. var theta = Math.atan2(vDir.z, vDir.x);
  58878. var phi = Math.acos(vDir.y);
  58879. while (theta < -Math.PI)
  58880. theta += 2 * Math.PI;
  58881. while (theta > Math.PI)
  58882. theta -= 2 * Math.PI;
  58883. var dx = theta / Math.PI;
  58884. var dy = phi / Math.PI;
  58885. // recenter.
  58886. dx = dx * 0.5 + 0.5;
  58887. var px = Math.round(dx * inputWidth);
  58888. if (px < 0)
  58889. px = 0;
  58890. else if (px >= inputWidth)
  58891. px = inputWidth - 1;
  58892. var py = Math.round(dy * inputHeight);
  58893. if (py < 0)
  58894. py = 0;
  58895. else if (py >= inputHeight)
  58896. py = inputHeight - 1;
  58897. var inputY = (inputHeight - py - 1);
  58898. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  58899. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  58900. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  58901. return {
  58902. r: r,
  58903. g: g,
  58904. b: b
  58905. };
  58906. };
  58907. PanoramaToCubeMapTools.FACE_FRONT = [
  58908. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58909. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58910. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58911. new BABYLON.Vector3(1.0, 1.0, -1.0)
  58912. ];
  58913. PanoramaToCubeMapTools.FACE_BACK = [
  58914. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58915. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58916. new BABYLON.Vector3(1.0, 1.0, 1.0),
  58917. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  58918. ];
  58919. PanoramaToCubeMapTools.FACE_RIGHT = [
  58920. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58921. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58922. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58923. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58924. ];
  58925. PanoramaToCubeMapTools.FACE_LEFT = [
  58926. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58927. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58928. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58929. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  58930. ];
  58931. PanoramaToCubeMapTools.FACE_DOWN = [
  58932. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58933. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58934. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58935. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58936. ];
  58937. PanoramaToCubeMapTools.FACE_UP = [
  58938. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58939. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58940. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58941. new BABYLON.Vector3(1.0, -1.0, -1.0)
  58942. ];
  58943. return PanoramaToCubeMapTools;
  58944. }());
  58945. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  58946. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58947. })(BABYLON || (BABYLON = {}));
  58948. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  58949. var BABYLON;
  58950. (function (BABYLON) {
  58951. var Internals;
  58952. (function (Internals) {
  58953. ;
  58954. /**
  58955. * This groups tools to convert HDR texture to native colors array.
  58956. */
  58957. var HDRTools = (function () {
  58958. function HDRTools() {
  58959. }
  58960. HDRTools.Ldexp = function (mantissa, exponent) {
  58961. if (exponent > 1023) {
  58962. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  58963. }
  58964. if (exponent < -1074) {
  58965. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  58966. }
  58967. return mantissa * Math.pow(2, exponent);
  58968. };
  58969. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  58970. if (exponent > 0) {
  58971. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  58972. float32array[index + 0] = red * exponent;
  58973. float32array[index + 1] = green * exponent;
  58974. float32array[index + 2] = blue * exponent;
  58975. }
  58976. else {
  58977. float32array[index + 0] = 0;
  58978. float32array[index + 1] = 0;
  58979. float32array[index + 2] = 0;
  58980. }
  58981. };
  58982. HDRTools.readStringLine = function (uint8array, startIndex) {
  58983. var line = "";
  58984. var character = "";
  58985. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  58986. character = String.fromCharCode(uint8array[i]);
  58987. if (character == "\n") {
  58988. break;
  58989. }
  58990. line += character;
  58991. }
  58992. return line;
  58993. };
  58994. /**
  58995. * Reads header information from an RGBE texture stored in a native array.
  58996. * More information on this format are available here:
  58997. * https://en.wikipedia.org/wiki/RGBE_image_format
  58998. *
  58999. * @param uint8array The binary file stored in native array.
  59000. * @return The header information.
  59001. */
  59002. HDRTools.RGBE_ReadHeader = function (uint8array) {
  59003. var height = 0;
  59004. var width = 0;
  59005. var line = this.readStringLine(uint8array, 0);
  59006. if (line[0] != '#' || line[1] != '?') {
  59007. throw "Bad HDR Format.";
  59008. }
  59009. var endOfHeader = false;
  59010. var findFormat = false;
  59011. var lineIndex = 0;
  59012. do {
  59013. lineIndex += (line.length + 1);
  59014. line = this.readStringLine(uint8array, lineIndex);
  59015. if (line == "FORMAT=32-bit_rle_rgbe") {
  59016. findFormat = true;
  59017. }
  59018. else if (line.length == 0) {
  59019. endOfHeader = true;
  59020. }
  59021. } while (!endOfHeader);
  59022. if (!findFormat) {
  59023. throw "HDR Bad header format, unsupported FORMAT";
  59024. }
  59025. lineIndex += (line.length + 1);
  59026. line = this.readStringLine(uint8array, lineIndex);
  59027. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  59028. var match = sizeRegexp.exec(line);
  59029. // TODO. Support +Y and -X if needed.
  59030. if (match.length < 3) {
  59031. throw "HDR Bad header format, no size";
  59032. }
  59033. width = parseInt(match[2]);
  59034. height = parseInt(match[1]);
  59035. if (width < 8 || width > 0x7fff) {
  59036. throw "HDR Bad header format, unsupported size";
  59037. }
  59038. lineIndex += (line.length + 1);
  59039. return {
  59040. height: height,
  59041. width: width,
  59042. dataPosition: lineIndex
  59043. };
  59044. };
  59045. /**
  59046. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  59047. * This RGBE texture needs to store the information as a panorama.
  59048. *
  59049. * More information on this format are available here:
  59050. * https://en.wikipedia.org/wiki/RGBE_image_format
  59051. *
  59052. * @param buffer The binary file stored in an array buffer.
  59053. * @param size The expected size of the extracted cubemap.
  59054. * @return The Cube Map information.
  59055. */
  59056. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  59057. var uint8array = new Uint8Array(buffer);
  59058. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  59059. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  59060. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  59061. return cubeMapData;
  59062. };
  59063. /**
  59064. * Returns the pixels data extracted from an RGBE texture.
  59065. * This pixels will be stored left to right up to down in the R G B order in one array.
  59066. *
  59067. * More information on this format are available here:
  59068. * https://en.wikipedia.org/wiki/RGBE_image_format
  59069. *
  59070. * @param uint8array The binary file stored in an array buffer.
  59071. * @param hdrInfo The header information of the file.
  59072. * @return The pixels data in RGB right to left up to down order.
  59073. */
  59074. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  59075. // Keep for multi format supports.
  59076. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  59077. };
  59078. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  59079. var num_scanlines = hdrInfo.height;
  59080. var scanline_width = hdrInfo.width;
  59081. var a, b, c, d, count;
  59082. var dataIndex = hdrInfo.dataPosition;
  59083. var index = 0, endIndex = 0, i = 0;
  59084. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  59085. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  59086. // 3 channels of 4 bytes per pixel in float.
  59087. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  59088. var resultArray = new Float32Array(resultBuffer);
  59089. // read in each successive scanline
  59090. while (num_scanlines > 0) {
  59091. a = uint8array[dataIndex++];
  59092. b = uint8array[dataIndex++];
  59093. c = uint8array[dataIndex++];
  59094. d = uint8array[dataIndex++];
  59095. if (a != 2 || b != 2 || (c & 0x80)) {
  59096. // this file is not run length encoded
  59097. throw "HDR Bad header format, not RLE";
  59098. }
  59099. if (((c << 8) | d) != scanline_width) {
  59100. throw "HDR Bad header format, wrong scan line width";
  59101. }
  59102. index = 0;
  59103. // read each of the four channels for the scanline into the buffer
  59104. for (i = 0; i < 4; i++) {
  59105. endIndex = (i + 1) * scanline_width;
  59106. while (index < endIndex) {
  59107. a = uint8array[dataIndex++];
  59108. b = uint8array[dataIndex++];
  59109. if (a > 128) {
  59110. // a run of the same value
  59111. count = a - 128;
  59112. if ((count == 0) || (count > endIndex - index)) {
  59113. throw "HDR Bad Format, bad scanline data (run)";
  59114. }
  59115. while (count-- > 0) {
  59116. scanLineArray[index++] = b;
  59117. }
  59118. }
  59119. else {
  59120. // a non-run
  59121. count = a;
  59122. if ((count == 0) || (count > endIndex - index)) {
  59123. throw "HDR Bad Format, bad scanline data (non-run)";
  59124. }
  59125. scanLineArray[index++] = b;
  59126. if (--count > 0) {
  59127. for (var j = 0; j < count; j++) {
  59128. scanLineArray[index++] = uint8array[dataIndex++];
  59129. }
  59130. }
  59131. }
  59132. }
  59133. }
  59134. // now convert data from buffer into floats
  59135. for (i = 0; i < scanline_width; i++) {
  59136. a = scanLineArray[i];
  59137. b = scanLineArray[i + scanline_width];
  59138. c = scanLineArray[i + 2 * scanline_width];
  59139. d = scanLineArray[i + 3 * scanline_width];
  59140. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  59141. }
  59142. num_scanlines--;
  59143. }
  59144. return resultArray;
  59145. };
  59146. return HDRTools;
  59147. }());
  59148. Internals.HDRTools = HDRTools;
  59149. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59150. })(BABYLON || (BABYLON = {}));
  59151. //# sourceMappingURL=babylon.hdr.js.map
  59152. var BABYLON;
  59153. (function (BABYLON) {
  59154. /**
  59155. * This represents a texture coming from an HDR input.
  59156. *
  59157. * The only supported format is currently panorama picture stored in RGBE format.
  59158. * Example of such files can be found on HDRLib: http://hdrlib.com/
  59159. */
  59160. var HDRCubeTexture = (function (_super) {
  59161. __extends(HDRCubeTexture, _super);
  59162. /**
  59163. * Instantiates an HDRTexture from the following parameters.
  59164. *
  59165. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  59166. * @param scene The scene the texture will be used in
  59167. * @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.
  59168. * @param noMipmap Forces to not generate the mipmap if true
  59169. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  59170. * @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)
  59171. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  59172. */
  59173. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  59174. if (noMipmap === void 0) { noMipmap = false; }
  59175. if (generateHarmonics === void 0) { generateHarmonics = true; }
  59176. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  59177. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  59178. if (onLoad === void 0) { onLoad = null; }
  59179. if (onError === void 0) { onError = null; }
  59180. var _this = _super.call(this, scene) || this;
  59181. _this._useInGammaSpace = false;
  59182. _this._generateHarmonics = true;
  59183. _this._isBABYLONPreprocessed = false;
  59184. _this._onLoad = null;
  59185. _this._onError = null;
  59186. /**
  59187. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  59188. */
  59189. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  59190. /**
  59191. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  59192. * This is usefull at run time to apply the good shader.
  59193. */
  59194. _this.isPMREM = false;
  59195. _this._isBlocking = true;
  59196. if (!url) {
  59197. return _this;
  59198. }
  59199. _this.name = url;
  59200. _this.url = url;
  59201. _this.hasAlpha = false;
  59202. _this.isCube = true;
  59203. _this._textureMatrix = BABYLON.Matrix.Identity();
  59204. _this._onLoad = onLoad;
  59205. _this._onError = onError;
  59206. _this.gammaSpace = false;
  59207. if (size) {
  59208. _this._isBABYLONPreprocessed = false;
  59209. _this._noMipmap = noMipmap;
  59210. _this._size = size;
  59211. _this._useInGammaSpace = useInGammaSpace;
  59212. _this._usePMREMGenerator = usePMREMGenerator &&
  59213. scene.getEngine().getCaps().textureLOD &&
  59214. _this.getScene().getEngine().getCaps().textureFloat &&
  59215. !_this._useInGammaSpace;
  59216. }
  59217. else {
  59218. _this._isBABYLONPreprocessed = true;
  59219. _this._noMipmap = false;
  59220. _this._useInGammaSpace = false;
  59221. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  59222. _this.getScene().getEngine().getCaps().textureFloat &&
  59223. !_this._useInGammaSpace;
  59224. }
  59225. _this.isPMREM = _this._usePMREMGenerator;
  59226. _this._texture = _this._getFromCache(url, _this._noMipmap);
  59227. if (!_this._texture) {
  59228. if (!scene.useDelayedTextureLoading) {
  59229. _this.loadTexture();
  59230. }
  59231. else {
  59232. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59233. }
  59234. }
  59235. return _this;
  59236. }
  59237. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  59238. /**
  59239. * Gets wether or not the texture is blocking during loading.
  59240. */
  59241. get: function () {
  59242. return this._isBlocking;
  59243. },
  59244. /**
  59245. * Sets wether or not the texture is blocking during loading.
  59246. */
  59247. set: function (value) {
  59248. this._isBlocking = value;
  59249. },
  59250. enumerable: true,
  59251. configurable: true
  59252. });
  59253. /**
  59254. * Occurs when the file is a preprocessed .babylon.hdr file.
  59255. */
  59256. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  59257. var _this = this;
  59258. var mipLevels = 0;
  59259. var floatArrayView = null;
  59260. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  59261. var mips = [];
  59262. var startIndex = 30;
  59263. for (var level = 0; level < mipLevels; level++) {
  59264. mips.push([]);
  59265. // Fill each pixel of the mip level.
  59266. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  59267. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59268. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  59269. mips[level].push(faceData);
  59270. startIndex += faceSize;
  59271. }
  59272. }
  59273. return mips;
  59274. } : null;
  59275. var callback = function (buffer) {
  59276. // Create Native Array Views
  59277. var intArrayView = new Int32Array(buffer);
  59278. floatArrayView = new Float32Array(buffer);
  59279. // Fill header.
  59280. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  59281. _this._size = intArrayView[1]; // CubeMap max mip face size.
  59282. // Update Texture Information.
  59283. _this._texture.updateSize(_this._size, _this._size);
  59284. // Fill polynomial information.
  59285. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59286. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59287. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59288. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59289. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59290. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59291. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59292. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59293. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59294. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59295. _this.sphericalPolynomial = sphericalPolynomial;
  59296. // Fill pixel data.
  59297. mipLevels = intArrayView[29]; // Number of mip levels.
  59298. var startIndex = 30;
  59299. var data = [];
  59300. var faceSize = Math.pow(_this._size, 2) * 3;
  59301. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59302. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59303. startIndex += faceSize;
  59304. }
  59305. var results = [];
  59306. var byteArray = null;
  59307. // Push each faces.
  59308. for (var k = 0; k < 6; k++) {
  59309. var dataFace = null;
  59310. // To be deprecated.
  59311. if (version === 1) {
  59312. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  59313. dataFace = data[j];
  59314. }
  59315. // If special cases.
  59316. if (!mipmapGenerator) {
  59317. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59318. // 3 channels of 1 bytes per pixel in bytes.
  59319. var byteBuffer = new ArrayBuffer(faceSize);
  59320. byteArray = new Uint8Array(byteBuffer);
  59321. }
  59322. for (var i = 0; i < _this._size * _this._size; i++) {
  59323. // Put in gamma space if requested.
  59324. if (_this._useInGammaSpace) {
  59325. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59326. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59327. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59328. }
  59329. // Convert to int texture for fallback.
  59330. if (byteArray) {
  59331. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59332. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59333. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59334. // May use luminance instead if the result is not accurate.
  59335. var max = Math.max(Math.max(r, g), b);
  59336. if (max > 255) {
  59337. var scale = 255 / max;
  59338. r *= scale;
  59339. g *= scale;
  59340. b *= scale;
  59341. }
  59342. byteArray[(i * 3) + 0] = r;
  59343. byteArray[(i * 3) + 1] = g;
  59344. byteArray[(i * 3) + 2] = b;
  59345. }
  59346. }
  59347. }
  59348. // Fill the array accordingly.
  59349. if (byteArray) {
  59350. results.push(byteArray);
  59351. }
  59352. else {
  59353. results.push(dataFace);
  59354. }
  59355. }
  59356. return results;
  59357. };
  59358. 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);
  59359. };
  59360. /**
  59361. * Occurs when the file is raw .hdr file.
  59362. */
  59363. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59364. var _this = this;
  59365. var callback = function (buffer) {
  59366. // Extract the raw linear data.
  59367. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59368. // Generate harmonics if needed.
  59369. if (_this._generateHarmonics) {
  59370. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59371. _this.sphericalPolynomial = sphericalPolynomial;
  59372. }
  59373. var results = [];
  59374. var byteArray = null;
  59375. // Push each faces.
  59376. for (var j = 0; j < 6; j++) {
  59377. // Create uintarray fallback.
  59378. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59379. // 3 channels of 1 bytes per pixel in bytes.
  59380. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59381. byteArray = new Uint8Array(byteBuffer);
  59382. }
  59383. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59384. // If special cases.
  59385. if (_this._useInGammaSpace || byteArray) {
  59386. for (var i = 0; i < _this._size * _this._size; i++) {
  59387. // Put in gamma space if requested.
  59388. if (_this._useInGammaSpace) {
  59389. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59390. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59391. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59392. }
  59393. // Convert to int texture for fallback.
  59394. if (byteArray) {
  59395. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59396. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59397. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59398. // May use luminance instead if the result is not accurate.
  59399. var max = Math.max(Math.max(r, g), b);
  59400. if (max > 255) {
  59401. var scale = 255 / max;
  59402. r *= scale;
  59403. g *= scale;
  59404. b *= scale;
  59405. }
  59406. byteArray[(i * 3) + 0] = r;
  59407. byteArray[(i * 3) + 1] = g;
  59408. byteArray[(i * 3) + 2] = b;
  59409. }
  59410. }
  59411. }
  59412. if (byteArray) {
  59413. results.push(byteArray);
  59414. }
  59415. else {
  59416. results.push(dataFace);
  59417. }
  59418. }
  59419. return results;
  59420. };
  59421. var mipmapGenerator = null;
  59422. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  59423. // if (!this._noMipmap &&
  59424. // this._usePMREMGenerator) {
  59425. // mipmapGenerator = (data: ArrayBufferView[]) => {
  59426. // // Custom setup of the generator matching with the PBR shader values.
  59427. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  59428. // this._size,
  59429. // this._size,
  59430. // 0,
  59431. // 3,
  59432. // this.getScene().getEngine().getCaps().textureFloat,
  59433. // 2048,
  59434. // 0.25,
  59435. // false,
  59436. // true);
  59437. // return generator.filterCubeMap();
  59438. // };
  59439. // }
  59440. 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);
  59441. };
  59442. /**
  59443. * Starts the loading process of the texture.
  59444. */
  59445. HDRCubeTexture.prototype.loadTexture = function () {
  59446. if (this._isBABYLONPreprocessed) {
  59447. this.loadBabylonTexture();
  59448. }
  59449. else {
  59450. this.loadHDRTexture();
  59451. }
  59452. };
  59453. HDRCubeTexture.prototype.clone = function () {
  59454. var size = this._isBABYLONPreprocessed ? null : this._size;
  59455. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  59456. // Base texture
  59457. newTexture.level = this.level;
  59458. newTexture.wrapU = this.wrapU;
  59459. newTexture.wrapV = this.wrapV;
  59460. newTexture.coordinatesIndex = this.coordinatesIndex;
  59461. newTexture.coordinatesMode = this.coordinatesMode;
  59462. return newTexture;
  59463. };
  59464. // Methods
  59465. HDRCubeTexture.prototype.delayLoad = function () {
  59466. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59467. return;
  59468. }
  59469. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59470. this._texture = this._getFromCache(this.url, this._noMipmap);
  59471. if (!this._texture) {
  59472. this.loadTexture();
  59473. }
  59474. };
  59475. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  59476. return this._textureMatrix;
  59477. };
  59478. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59479. this._textureMatrix = value;
  59480. };
  59481. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59482. var texture = null;
  59483. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59484. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  59485. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  59486. texture.name = parsedTexture.name;
  59487. texture.hasAlpha = parsedTexture.hasAlpha;
  59488. texture.level = parsedTexture.level;
  59489. texture.coordinatesMode = parsedTexture.coordinatesMode;
  59490. texture.isBlocking = parsedTexture.isBlocking;
  59491. }
  59492. return texture;
  59493. };
  59494. HDRCubeTexture.prototype.serialize = function () {
  59495. if (!this.name) {
  59496. return null;
  59497. }
  59498. var serializationObject = {};
  59499. serializationObject.name = this.name;
  59500. serializationObject.hasAlpha = this.hasAlpha;
  59501. serializationObject.isCube = true;
  59502. serializationObject.level = this.level;
  59503. serializationObject.size = this._size;
  59504. serializationObject.coordinatesMode = this.coordinatesMode;
  59505. serializationObject.useInGammaSpace = this._useInGammaSpace;
  59506. serializationObject.generateHarmonics = this._generateHarmonics;
  59507. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  59508. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  59509. serializationObject.customType = "BABYLON.HDRCubeTexture";
  59510. serializationObject.noMipmap = this._noMipmap;
  59511. serializationObject.isBlocking = this._isBlocking;
  59512. return serializationObject;
  59513. };
  59514. /**
  59515. * Saves as a file the data contained in the texture in a binary format.
  59516. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59517. * as the spherical used in the lighting.
  59518. * @param url The HDR file url.
  59519. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59520. * @param onError Method called if any error happens during download.
  59521. * @return The packed binary data.
  59522. */
  59523. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  59524. if (onError === void 0) { onError = null; }
  59525. var callback = function (buffer) {
  59526. var data = new Blob([buffer], { type: 'application/octet-stream' });
  59527. // Returns a URL you can use as a href.
  59528. var objUrl = window.URL.createObjectURL(data);
  59529. // Simulates a link to it and click to dowload.
  59530. var a = document.createElement("a");
  59531. document.body.appendChild(a);
  59532. a.style.display = "none";
  59533. a.href = objUrl;
  59534. a.download = "envmap.babylon.hdr";
  59535. a.click();
  59536. };
  59537. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  59538. };
  59539. /**
  59540. * Serializes the data contained in the texture in a binary format.
  59541. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59542. * as the spherical used in the lighting.
  59543. * @param url The HDR file url.
  59544. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59545. * @param onError Method called if any error happens during download.
  59546. * @return The packed binary data.
  59547. */
  59548. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59549. if (onError === void 0) { onError = null; }
  59550. // Needs the url tho create the texture.
  59551. if (!url) {
  59552. return null;
  59553. }
  59554. // Check Power of two size.
  59555. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59556. return null;
  59557. }
  59558. // Coming Back in 3.1.
  59559. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  59560. return null;
  59561. };
  59562. HDRCubeTexture._facesMapping = [
  59563. "right",
  59564. "left",
  59565. "up",
  59566. "down",
  59567. "front",
  59568. "back"
  59569. ];
  59570. return HDRCubeTexture;
  59571. }(BABYLON.BaseTexture));
  59572. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59573. })(BABYLON || (BABYLON = {}));
  59574. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  59575. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  59576. // Huge respect for a such great lib.
  59577. // Earcut license:
  59578. // Copyright (c) 2016, Mapbox
  59579. //
  59580. // Permission to use, copy, modify, and/or distribute this software for any purpose
  59581. // with or without fee is hereby granted, provided that the above copyright notice
  59582. // and this permission notice appear in all copies.
  59583. //
  59584. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  59585. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  59586. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  59587. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  59588. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  59589. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  59590. // THIS SOFTWARE.
  59591. var Earcut;
  59592. (function (Earcut) {
  59593. /**
  59594. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  59595. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  59596. * @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).
  59597. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  59598. */
  59599. function earcut(data, holeIndices, dim) {
  59600. dim = dim || 2;
  59601. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  59602. if (!outerNode)
  59603. return triangles;
  59604. var minX, minY, maxX, maxY, x, y, size;
  59605. if (hasHoles)
  59606. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  59607. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  59608. if (data.length > 80 * dim) {
  59609. minX = maxX = data[0];
  59610. minY = maxY = data[1];
  59611. for (var i = dim; i < outerLen; i += dim) {
  59612. x = data[i];
  59613. y = data[i + 1];
  59614. if (x < minX)
  59615. minX = x;
  59616. if (y < minY)
  59617. minY = y;
  59618. if (x > maxX)
  59619. maxX = x;
  59620. if (y > maxY)
  59621. maxY = y;
  59622. }
  59623. // minX, minY and size are later used to transform coords into integers for z-order calculation
  59624. size = Math.max(maxX - minX, maxY - minY);
  59625. }
  59626. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  59627. return triangles;
  59628. }
  59629. Earcut.earcut = earcut;
  59630. // create a circular doubly linked list from polygon points in the specified winding order
  59631. function linkedList(data, start, end, dim, clockwise) {
  59632. var i, last;
  59633. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  59634. for (i = start; i < end; i += dim)
  59635. last = insertNode(i, data[i], data[i + 1], last);
  59636. }
  59637. else {
  59638. for (i = end - dim; i >= start; i -= dim)
  59639. last = insertNode(i, data[i], data[i + 1], last);
  59640. }
  59641. if (last && equals(last, last.next)) {
  59642. removeNode(last);
  59643. last = last.next;
  59644. }
  59645. return last;
  59646. }
  59647. // eliminate colinear or duplicate points
  59648. function filterPoints(start, end) {
  59649. if (!start)
  59650. return start;
  59651. if (!end)
  59652. end = start;
  59653. var p = start, again;
  59654. do {
  59655. again = false;
  59656. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  59657. removeNode(p);
  59658. p = end = p.prev;
  59659. if (p === p.next)
  59660. return null;
  59661. again = true;
  59662. }
  59663. else {
  59664. p = p.next;
  59665. }
  59666. } while (again || p !== end);
  59667. return end;
  59668. }
  59669. // main ear slicing loop which triangulates a polygon (given as a linked list)
  59670. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  59671. if (!ear)
  59672. return;
  59673. // interlink polygon nodes in z-order
  59674. if (!pass && size)
  59675. indexCurve(ear, minX, minY, size);
  59676. var stop = ear, prev, next;
  59677. // iterate through ears, slicing them one by one
  59678. while (ear.prev !== ear.next) {
  59679. prev = ear.prev;
  59680. next = ear.next;
  59681. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  59682. // cut off the triangle
  59683. triangles.push(prev.i / dim);
  59684. triangles.push(ear.i / dim);
  59685. triangles.push(next.i / dim);
  59686. removeNode(ear);
  59687. // skipping the next vertice leads to less sliver triangles
  59688. ear = next.next;
  59689. stop = next.next;
  59690. continue;
  59691. }
  59692. ear = next;
  59693. // if we looped through the whole remaining polygon and can't find any more ears
  59694. if (ear === stop) {
  59695. // try filtering points and slicing again
  59696. if (!pass) {
  59697. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  59698. // if this didn't work, try curing all small self-intersections locally
  59699. }
  59700. else if (pass === 1) {
  59701. ear = cureLocalIntersections(ear, triangles, dim);
  59702. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  59703. // as a last resort, try splitting the remaining polygon into two
  59704. }
  59705. else if (pass === 2) {
  59706. splitEarcut(ear, triangles, dim, minX, minY, size);
  59707. }
  59708. break;
  59709. }
  59710. }
  59711. }
  59712. // check whether a polygon node forms a valid ear with adjacent nodes
  59713. function isEar(ear) {
  59714. var a = ear.prev, b = ear, c = ear.next;
  59715. if (area(a, b, c) >= 0)
  59716. return false; // reflex, can't be an ear
  59717. // now make sure we don't have other points inside the potential ear
  59718. var p = ear.next.next;
  59719. while (p !== ear.prev) {
  59720. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59721. area(p.prev, p, p.next) >= 0)
  59722. return false;
  59723. p = p.next;
  59724. }
  59725. return true;
  59726. }
  59727. function isEarHashed(ear, minX, minY, size) {
  59728. var a = ear.prev, b = ear, c = ear.next;
  59729. if (area(a, b, c) >= 0)
  59730. return false; // reflex, can't be an ear
  59731. // triangle bbox; min & max are calculated like this for speed
  59732. 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);
  59733. // z-order range for the current triangle bbox;
  59734. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  59735. // first look for points inside the triangle in increasing z-order
  59736. var p = ear.nextZ;
  59737. while (p && p.z <= maxZ) {
  59738. if (p !== ear.prev &&
  59739. p !== ear.next &&
  59740. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59741. area(p.prev, p, p.next) >= 0)
  59742. return false;
  59743. p = p.nextZ;
  59744. }
  59745. // then look for points in decreasing z-order
  59746. p = ear.prevZ;
  59747. while (p && p.z >= minZ) {
  59748. if (p !== ear.prev &&
  59749. p !== ear.next &&
  59750. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59751. area(p.prev, p, p.next) >= 0)
  59752. return false;
  59753. p = p.prevZ;
  59754. }
  59755. return true;
  59756. }
  59757. // go through all polygon nodes and cure small local self-intersections
  59758. function cureLocalIntersections(start, triangles, dim) {
  59759. var p = start;
  59760. do {
  59761. var a = p.prev, b = p.next.next;
  59762. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  59763. triangles.push(a.i / dim);
  59764. triangles.push(p.i / dim);
  59765. triangles.push(b.i / dim);
  59766. // remove two nodes involved
  59767. removeNode(p);
  59768. removeNode(p.next);
  59769. p = start = b;
  59770. }
  59771. p = p.next;
  59772. } while (p !== start);
  59773. return p;
  59774. }
  59775. // try splitting polygon into two and triangulate them independently
  59776. function splitEarcut(start, triangles, dim, minX, minY, size) {
  59777. // look for a valid diagonal that divides the polygon into two
  59778. var a = start;
  59779. do {
  59780. var b = a.next.next;
  59781. while (b !== a.prev) {
  59782. if (a.i !== b.i && isValidDiagonal(a, b)) {
  59783. // split the polygon in two by the diagonal
  59784. var c = splitPolygon(a, b);
  59785. // filter colinear points around the cuts
  59786. a = filterPoints(a, a.next);
  59787. c = filterPoints(c, c.next);
  59788. // run earcut on each half
  59789. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  59790. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  59791. return;
  59792. }
  59793. b = b.next;
  59794. }
  59795. a = a.next;
  59796. } while (a !== start);
  59797. }
  59798. // link every hole into the outer loop, producing a single-ring polygon without holes
  59799. function eliminateHoles(data, holeIndices, outerNode, dim) {
  59800. var queue = [], i, len, start, end, list;
  59801. for (i = 0, len = holeIndices.length; i < len; i++) {
  59802. start = holeIndices[i] * dim;
  59803. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  59804. list = linkedList(data, start, end, dim, false);
  59805. if (list === list.next)
  59806. list.steiner = true;
  59807. queue.push(getLeftmost(list));
  59808. }
  59809. queue.sort(compareX);
  59810. // process holes from left to right
  59811. for (i = 0; i < queue.length; i++) {
  59812. eliminateHole(queue[i], outerNode);
  59813. outerNode = filterPoints(outerNode, outerNode.next);
  59814. }
  59815. return outerNode;
  59816. }
  59817. function compareX(a, b) {
  59818. return a.x - b.x;
  59819. }
  59820. // find a bridge between vertices that connects hole with an outer ring and and link it
  59821. function eliminateHole(hole, outerNode) {
  59822. outerNode = findHoleBridge(hole, outerNode);
  59823. if (outerNode) {
  59824. var b = splitPolygon(outerNode, hole);
  59825. filterPoints(b, b.next);
  59826. }
  59827. }
  59828. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  59829. function findHoleBridge(hole, outerNode) {
  59830. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  59831. // find a segment intersected by a ray from the hole's leftmost point to the left;
  59832. // segment's endpoint with lesser x will be potential connection point
  59833. do {
  59834. if (hy <= p.y && hy >= p.next.y) {
  59835. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  59836. if (x <= hx && x > qx) {
  59837. qx = x;
  59838. if (x === hx) {
  59839. if (hy === p.y)
  59840. return p;
  59841. if (hy === p.next.y)
  59842. return p.next;
  59843. }
  59844. m = p.x < p.next.x ? p : p.next;
  59845. }
  59846. }
  59847. p = p.next;
  59848. } while (p !== outerNode);
  59849. if (!m)
  59850. return null;
  59851. if (hx === qx)
  59852. return m.prev; // hole touches outer segment; pick lower endpoint
  59853. // look for points inside the triangle of hole point, segment intersection and endpoint;
  59854. // if there are no points found, we have a valid connection;
  59855. // otherwise choose the point of the minimum angle with the ray as connection point
  59856. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  59857. p = m.next;
  59858. while (p !== stop) {
  59859. if (hx >= p.x &&
  59860. p.x >= mx &&
  59861. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  59862. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  59863. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  59864. m = p;
  59865. tanMin = tan;
  59866. }
  59867. }
  59868. p = p.next;
  59869. }
  59870. return m;
  59871. }
  59872. // interlink polygon nodes in z-order
  59873. function indexCurve(start, minX, minY, size) {
  59874. var p = start;
  59875. do {
  59876. if (p.z === null)
  59877. p.z = zOrder(p.x, p.y, minX, minY, size);
  59878. p.prevZ = p.prev;
  59879. p.nextZ = p.next;
  59880. p = p.next;
  59881. } while (p !== start);
  59882. p.prevZ.nextZ = null;
  59883. p.prevZ = null;
  59884. sortLinked(p);
  59885. }
  59886. // Simon Tatham's linked list merge sort algorithm
  59887. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  59888. function sortLinked(list) {
  59889. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  59890. do {
  59891. p = list;
  59892. list = null;
  59893. tail = null;
  59894. numMerges = 0;
  59895. while (p) {
  59896. numMerges++;
  59897. q = p;
  59898. pSize = 0;
  59899. for (i = 0; i < inSize; i++) {
  59900. pSize++;
  59901. q = q.nextZ;
  59902. if (!q)
  59903. break;
  59904. }
  59905. qSize = inSize;
  59906. while (pSize > 0 || (qSize > 0 && q)) {
  59907. if (pSize === 0) {
  59908. e = q;
  59909. q = q.nextZ;
  59910. qSize--;
  59911. }
  59912. else if (qSize === 0 || !q) {
  59913. e = p;
  59914. p = p.nextZ;
  59915. pSize--;
  59916. }
  59917. else if (p.z <= q.z) {
  59918. e = p;
  59919. p = p.nextZ;
  59920. pSize--;
  59921. }
  59922. else {
  59923. e = q;
  59924. q = q.nextZ;
  59925. qSize--;
  59926. }
  59927. if (tail)
  59928. tail.nextZ = e;
  59929. else
  59930. list = e;
  59931. e.prevZ = tail;
  59932. tail = e;
  59933. }
  59934. p = q;
  59935. }
  59936. tail.nextZ = null;
  59937. inSize *= 2;
  59938. } while (numMerges > 1);
  59939. return list;
  59940. }
  59941. // z-order of a point given coords and size of the data bounding box
  59942. function zOrder(x, y, minX, minY, size) {
  59943. // coords are transformed into non-negative 15-bit integer range
  59944. x = 32767 * (x - minX) / size;
  59945. y = 32767 * (y - minY) / size;
  59946. x = (x | (x << 8)) & 0x00FF00FF;
  59947. x = (x | (x << 4)) & 0x0F0F0F0F;
  59948. x = (x | (x << 2)) & 0x33333333;
  59949. x = (x | (x << 1)) & 0x55555555;
  59950. y = (y | (y << 8)) & 0x00FF00FF;
  59951. y = (y | (y << 4)) & 0x0F0F0F0F;
  59952. y = (y | (y << 2)) & 0x33333333;
  59953. y = (y | (y << 1)) & 0x55555555;
  59954. return x | (y << 1);
  59955. }
  59956. // find the leftmost node of a polygon ring
  59957. function getLeftmost(start) {
  59958. var p = start, leftmost = start;
  59959. do {
  59960. if (p.x < leftmost.x)
  59961. leftmost = p;
  59962. p = p.next;
  59963. } while (p !== start);
  59964. return leftmost;
  59965. }
  59966. // check if a point lies within a convex triangle
  59967. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  59968. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  59969. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  59970. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  59971. }
  59972. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  59973. function isValidDiagonal(a, b) {
  59974. return a.next.i !== b.i &&
  59975. a.prev.i !== b.i &&
  59976. !intersectsPolygon(a, b) &&
  59977. locallyInside(a, b) &&
  59978. locallyInside(b, a) &&
  59979. middleInside(a, b);
  59980. }
  59981. // signed area of a triangle
  59982. function area(p, q, r) {
  59983. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  59984. }
  59985. // check if two points are equal
  59986. function equals(p1, p2) {
  59987. return p1.x === p2.x && p1.y === p2.y;
  59988. }
  59989. // check if two segments intersect
  59990. function intersects(p1, q1, p2, q2) {
  59991. if ((equals(p1, q1) && equals(p2, q2)) ||
  59992. (equals(p1, q2) && equals(p2, q1)))
  59993. return true;
  59994. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  59995. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  59996. }
  59997. // check if a polygon diagonal intersects any polygon segments
  59998. function intersectsPolygon(a, b) {
  59999. var p = a;
  60000. do {
  60001. if (p.i !== a.i &&
  60002. p.next.i !== a.i &&
  60003. p.i !== b.i &&
  60004. p.next.i !== b.i &&
  60005. intersects(p, p.next, a, b))
  60006. return true;
  60007. p = p.next;
  60008. } while (p !== a);
  60009. return false;
  60010. }
  60011. // check if a polygon diagonal is locally inside the polygon
  60012. function locallyInside(a, b) {
  60013. return area(a.prev, a, a.next) < 0
  60014. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  60015. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  60016. }
  60017. // check if the middle point of a polygon diagonal is inside the polygon
  60018. function middleInside(a, b) {
  60019. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  60020. do {
  60021. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  60022. inside = !inside;
  60023. p = p.next;
  60024. } while (p !== a);
  60025. return inside;
  60026. }
  60027. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  60028. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  60029. function splitPolygon(a, b) {
  60030. 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;
  60031. a.next = b;
  60032. b.prev = a;
  60033. a2.next = an;
  60034. an.prev = a2;
  60035. b2.next = a2;
  60036. a2.prev = b2;
  60037. bp.next = b2;
  60038. b2.prev = bp;
  60039. return b2;
  60040. }
  60041. // create a node and optionally link it with previous one (in a circular doubly linked list)
  60042. function insertNode(i, x, y, last) {
  60043. var p = new Node(i, x, y);
  60044. if (!last) {
  60045. p.prev = p;
  60046. p.next = p;
  60047. }
  60048. else {
  60049. p.next = last.next;
  60050. p.prev = last;
  60051. last.next.prev = p;
  60052. last.next = p;
  60053. }
  60054. return p;
  60055. }
  60056. function removeNode(p) {
  60057. p.next.prev = p.prev;
  60058. p.prev.next = p.next;
  60059. if (p.prevZ)
  60060. p.prevZ.nextZ = p.nextZ;
  60061. if (p.nextZ)
  60062. p.nextZ.prevZ = p.prevZ;
  60063. }
  60064. function Node(i, x, y) {
  60065. // vertice index in coordinates array
  60066. this.i = i;
  60067. // vertex coordinates
  60068. this.x = x;
  60069. this.y = y;
  60070. // previous and next vertice nodes in a polygon ring
  60071. this.prev = null;
  60072. this.next = null;
  60073. // z-order curve value
  60074. this.z = null;
  60075. // previous and next nodes in z-order
  60076. this.prevZ = null;
  60077. this.nextZ = null;
  60078. // indicates whether this is a steiner point
  60079. this.steiner = false;
  60080. }
  60081. /**
  60082. * return a percentage difference between the polygon area and its triangulation area;
  60083. * used to verify correctness of triangulation
  60084. */
  60085. function deviation(data, holeIndices, dim, triangles) {
  60086. var hasHoles = holeIndices && holeIndices.length;
  60087. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  60088. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  60089. if (hasHoles) {
  60090. for (var i = 0, len = holeIndices.length; i < len; i++) {
  60091. var start = holeIndices[i] * dim;
  60092. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  60093. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  60094. }
  60095. }
  60096. var trianglesArea = 0;
  60097. for (i = 0; i < triangles.length; i += 3) {
  60098. var a = triangles[i] * dim;
  60099. var b = triangles[i + 1] * dim;
  60100. var c = triangles[i + 2] * dim;
  60101. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  60102. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  60103. }
  60104. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  60105. }
  60106. Earcut.deviation = deviation;
  60107. ;
  60108. function signedArea(data, start, end, dim) {
  60109. var sum = 0;
  60110. for (var i = start, j = end - dim; i < end; i += dim) {
  60111. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  60112. j = i;
  60113. }
  60114. return sum;
  60115. }
  60116. /**
  60117. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  60118. */
  60119. function flatten(data) {
  60120. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  60121. for (var i = 0; i < data.length; i++) {
  60122. for (var j = 0; j < data[i].length; j++) {
  60123. for (var d = 0; d < dim; d++)
  60124. result.vertices.push(data[i][j][d]);
  60125. }
  60126. if (i > 0) {
  60127. holeIndex += data[i - 1].length;
  60128. result.holes.push(holeIndex);
  60129. }
  60130. }
  60131. return result;
  60132. }
  60133. Earcut.flatten = flatten;
  60134. ;
  60135. })(Earcut || (Earcut = {}));
  60136. //# sourceMappingURL=babylon.earcut.js.map
  60137. /// <reference path="..\Math\babylon.math.ts" />
  60138. var BABYLON;
  60139. (function (BABYLON) {
  60140. var IndexedVector2 = (function (_super) {
  60141. __extends(IndexedVector2, _super);
  60142. function IndexedVector2(original, index) {
  60143. var _this = _super.call(this, original.x, original.y) || this;
  60144. _this.index = index;
  60145. return _this;
  60146. }
  60147. return IndexedVector2;
  60148. }(BABYLON.Vector2));
  60149. var PolygonPoints = (function () {
  60150. function PolygonPoints() {
  60151. this.elements = new Array();
  60152. }
  60153. PolygonPoints.prototype.add = function (originalPoints) {
  60154. var _this = this;
  60155. var result = new Array();
  60156. originalPoints.forEach(function (point) {
  60157. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  60158. var newPoint = new IndexedVector2(point, _this.elements.length);
  60159. result.push(newPoint);
  60160. _this.elements.push(newPoint);
  60161. }
  60162. });
  60163. return result;
  60164. };
  60165. PolygonPoints.prototype.computeBounds = function () {
  60166. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  60167. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  60168. this.elements.forEach(function (point) {
  60169. // x
  60170. if (point.x < lmin.x) {
  60171. lmin.x = point.x;
  60172. }
  60173. else if (point.x > lmax.x) {
  60174. lmax.x = point.x;
  60175. }
  60176. // y
  60177. if (point.y < lmin.y) {
  60178. lmin.y = point.y;
  60179. }
  60180. else if (point.y > lmax.y) {
  60181. lmax.y = point.y;
  60182. }
  60183. });
  60184. return {
  60185. min: lmin,
  60186. max: lmax,
  60187. width: lmax.x - lmin.x,
  60188. height: lmax.y - lmin.y
  60189. };
  60190. };
  60191. return PolygonPoints;
  60192. }());
  60193. var Polygon = (function () {
  60194. function Polygon() {
  60195. }
  60196. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  60197. return [
  60198. new BABYLON.Vector2(xmin, ymin),
  60199. new BABYLON.Vector2(xmax, ymin),
  60200. new BABYLON.Vector2(xmax, ymax),
  60201. new BABYLON.Vector2(xmin, ymax)
  60202. ];
  60203. };
  60204. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  60205. if (cx === void 0) { cx = 0; }
  60206. if (cy === void 0) { cy = 0; }
  60207. if (numberOfSides === void 0) { numberOfSides = 32; }
  60208. var result = new Array();
  60209. var angle = 0;
  60210. var increment = (Math.PI * 2) / numberOfSides;
  60211. for (var i = 0; i < numberOfSides; i++) {
  60212. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  60213. angle -= increment;
  60214. }
  60215. return result;
  60216. };
  60217. Polygon.Parse = function (input) {
  60218. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  60219. var i, result = [];
  60220. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  60221. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  60222. }
  60223. return result;
  60224. };
  60225. Polygon.StartingAt = function (x, y) {
  60226. return BABYLON.Path2.StartingAt(x, y);
  60227. };
  60228. return Polygon;
  60229. }());
  60230. BABYLON.Polygon = Polygon;
  60231. var PolygonMeshBuilder = (function () {
  60232. function PolygonMeshBuilder(name, contours, scene) {
  60233. this._points = new PolygonPoints();
  60234. this._outlinepoints = new PolygonPoints();
  60235. this._holes = [];
  60236. this._epoints = new Array();
  60237. this._eholes = new Array();
  60238. this._name = name;
  60239. this._scene = scene;
  60240. var points;
  60241. if (contours instanceof BABYLON.Path2) {
  60242. points = contours.getPoints();
  60243. }
  60244. else {
  60245. points = contours;
  60246. }
  60247. this._addToepoint(points);
  60248. this._points.add(points);
  60249. this._outlinepoints.add(points);
  60250. }
  60251. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  60252. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  60253. var p = points_1[_i];
  60254. this._epoints.push(p.x, p.y);
  60255. }
  60256. };
  60257. PolygonMeshBuilder.prototype.addHole = function (hole) {
  60258. this._points.add(hole);
  60259. var holepoints = new PolygonPoints();
  60260. holepoints.add(hole);
  60261. this._holes.push(holepoints);
  60262. this._eholes.push(this._epoints.length / 2);
  60263. this._addToepoint(hole);
  60264. return this;
  60265. };
  60266. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  60267. var _this = this;
  60268. if (updatable === void 0) { updatable = false; }
  60269. var result = new BABYLON.Mesh(this._name, this._scene);
  60270. var normals = [];
  60271. var positions = [];
  60272. var uvs = [];
  60273. var bounds = this._points.computeBounds();
  60274. this._points.elements.forEach(function (p) {
  60275. normals.push(0, 1.0, 0);
  60276. positions.push(p.x, 0, p.y);
  60277. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  60278. });
  60279. var indices = [];
  60280. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  60281. for (var i = 0; i < res.length; i++) {
  60282. indices.push(res[i]);
  60283. }
  60284. if (depth > 0) {
  60285. var positionscount = (positions.length / 3); //get the current pointcount
  60286. this._points.elements.forEach(function (p) {
  60287. normals.push(0, -1.0, 0);
  60288. positions.push(p.x, -depth, p.y);
  60289. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  60290. });
  60291. var totalCount = indices.length;
  60292. for (var i = 0; i < totalCount; i += 3) {
  60293. var i0 = indices[i + 0];
  60294. var i1 = indices[i + 1];
  60295. var i2 = indices[i + 2];
  60296. indices.push(i2 + positionscount);
  60297. indices.push(i1 + positionscount);
  60298. indices.push(i0 + positionscount);
  60299. }
  60300. //Add the sides
  60301. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  60302. this._holes.forEach(function (hole) {
  60303. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  60304. });
  60305. }
  60306. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  60307. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  60308. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  60309. result.setIndices(indices);
  60310. return result;
  60311. };
  60312. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  60313. var StartIndex = positions.length / 3;
  60314. var ulength = 0;
  60315. for (var i = 0; i < points.elements.length; i++) {
  60316. var p = points.elements[i];
  60317. var p1;
  60318. if ((i + 1) > points.elements.length - 1) {
  60319. p1 = points.elements[0];
  60320. }
  60321. else {
  60322. p1 = points.elements[i + 1];
  60323. }
  60324. positions.push(p.x, 0, p.y);
  60325. positions.push(p.x, -depth, p.y);
  60326. positions.push(p1.x, 0, p1.y);
  60327. positions.push(p1.x, -depth, p1.y);
  60328. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  60329. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  60330. var v3 = v2.subtract(v1);
  60331. var v4 = new BABYLON.Vector3(0, 1, 0);
  60332. var vn = BABYLON.Vector3.Cross(v3, v4);
  60333. vn = vn.normalize();
  60334. uvs.push(ulength / bounds.width, 0);
  60335. uvs.push(ulength / bounds.width, 1);
  60336. ulength += v3.length();
  60337. uvs.push((ulength / bounds.width), 0);
  60338. uvs.push((ulength / bounds.width), 1);
  60339. if (!flip) {
  60340. normals.push(-vn.x, -vn.y, -vn.z);
  60341. normals.push(-vn.x, -vn.y, -vn.z);
  60342. normals.push(-vn.x, -vn.y, -vn.z);
  60343. normals.push(-vn.x, -vn.y, -vn.z);
  60344. indices.push(StartIndex);
  60345. indices.push(StartIndex + 1);
  60346. indices.push(StartIndex + 2);
  60347. indices.push(StartIndex + 1);
  60348. indices.push(StartIndex + 3);
  60349. indices.push(StartIndex + 2);
  60350. }
  60351. else {
  60352. normals.push(vn.x, vn.y, vn.z);
  60353. normals.push(vn.x, vn.y, vn.z);
  60354. normals.push(vn.x, vn.y, vn.z);
  60355. normals.push(vn.x, vn.y, vn.z);
  60356. indices.push(StartIndex);
  60357. indices.push(StartIndex + 2);
  60358. indices.push(StartIndex + 1);
  60359. indices.push(StartIndex + 1);
  60360. indices.push(StartIndex + 2);
  60361. indices.push(StartIndex + 3);
  60362. }
  60363. StartIndex += 4;
  60364. }
  60365. ;
  60366. };
  60367. return PolygonMeshBuilder;
  60368. }());
  60369. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  60370. })(BABYLON || (BABYLON = {}));
  60371. //# sourceMappingURL=babylon.polygonMesh.js.map
  60372. var BABYLON;
  60373. (function (BABYLON) {
  60374. // Unique ID when we import meshes from Babylon to CSG
  60375. var currentCSGMeshId = 0;
  60376. // # class Vertex
  60377. // Represents a vertex of a polygon. Use your own vertex class instead of this
  60378. // one to provide additional features like texture coordinates and vertex
  60379. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  60380. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  60381. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  60382. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  60383. // is not used anywhere else.
  60384. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  60385. var Vertex = (function () {
  60386. function Vertex(pos, normal, uv) {
  60387. this.pos = pos;
  60388. this.normal = normal;
  60389. this.uv = uv;
  60390. }
  60391. Vertex.prototype.clone = function () {
  60392. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  60393. };
  60394. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  60395. // orientation of a polygon is flipped.
  60396. Vertex.prototype.flip = function () {
  60397. this.normal = this.normal.scale(-1);
  60398. };
  60399. // Create a new vertex between this vertex and `other` by linearly
  60400. // interpolating all properties using a parameter of `t`. Subclasses should
  60401. // override this to interpolate additional properties.
  60402. Vertex.prototype.interpolate = function (other, t) {
  60403. 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));
  60404. };
  60405. return Vertex;
  60406. }());
  60407. // # class Plane
  60408. // Represents a plane in 3D space.
  60409. var Plane = (function () {
  60410. function Plane(normal, w) {
  60411. this.normal = normal;
  60412. this.w = w;
  60413. }
  60414. Plane.FromPoints = function (a, b, c) {
  60415. var v0 = c.subtract(a);
  60416. var v1 = b.subtract(a);
  60417. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  60418. return null;
  60419. }
  60420. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  60421. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  60422. };
  60423. Plane.prototype.clone = function () {
  60424. return new Plane(this.normal.clone(), this.w);
  60425. };
  60426. Plane.prototype.flip = function () {
  60427. this.normal.scaleInPlace(-1);
  60428. this.w = -this.w;
  60429. };
  60430. // Split `polygon` by this plane if needed, then put the polygon or polygon
  60431. // fragments in the appropriate lists. Coplanar polygons go into either
  60432. // `coplanarFront` or `coplanarBack` depending on their orientation with
  60433. // respect to this plane. Polygons in front or in back of this plane go into
  60434. // either `front` or `back`.
  60435. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  60436. var COPLANAR = 0;
  60437. var FRONT = 1;
  60438. var BACK = 2;
  60439. var SPANNING = 3;
  60440. // Classify each point as well as the entire polygon into one of the above
  60441. // four classes.
  60442. var polygonType = 0;
  60443. var types = [];
  60444. var i;
  60445. var t;
  60446. for (i = 0; i < polygon.vertices.length; i++) {
  60447. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  60448. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  60449. polygonType |= type;
  60450. types.push(type);
  60451. }
  60452. // Put the polygon in the correct list, splitting it when necessary.
  60453. switch (polygonType) {
  60454. case COPLANAR:
  60455. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  60456. break;
  60457. case FRONT:
  60458. front.push(polygon);
  60459. break;
  60460. case BACK:
  60461. back.push(polygon);
  60462. break;
  60463. case SPANNING:
  60464. var f = [], b = [];
  60465. for (i = 0; i < polygon.vertices.length; i++) {
  60466. var j = (i + 1) % polygon.vertices.length;
  60467. var ti = types[i], tj = types[j];
  60468. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  60469. if (ti !== BACK)
  60470. f.push(vi);
  60471. if (ti !== FRONT)
  60472. b.push(ti !== BACK ? vi.clone() : vi);
  60473. if ((ti | tj) === SPANNING) {
  60474. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  60475. var v = vi.interpolate(vj, t);
  60476. f.push(v);
  60477. b.push(v.clone());
  60478. }
  60479. }
  60480. var poly;
  60481. if (f.length >= 3) {
  60482. poly = new Polygon(f, polygon.shared);
  60483. if (poly.plane)
  60484. front.push(poly);
  60485. }
  60486. if (b.length >= 3) {
  60487. poly = new Polygon(b, polygon.shared);
  60488. if (poly.plane)
  60489. back.push(poly);
  60490. }
  60491. break;
  60492. }
  60493. };
  60494. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  60495. // point is on the plane.
  60496. Plane.EPSILON = 1e-5;
  60497. return Plane;
  60498. }());
  60499. // # class Polygon
  60500. // Represents a convex polygon. The vertices used to initialize a polygon must
  60501. // be coplanar and form a convex loop.
  60502. //
  60503. // Each convex polygon has a `shared` property, which is shared between all
  60504. // polygons that are clones of each other or were split from the same polygon.
  60505. // This can be used to define per-polygon properties (such as surface color).
  60506. var Polygon = (function () {
  60507. function Polygon(vertices, shared) {
  60508. this.vertices = vertices;
  60509. this.shared = shared;
  60510. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  60511. }
  60512. Polygon.prototype.clone = function () {
  60513. var vertices = this.vertices.map(function (v) { return v.clone(); });
  60514. return new Polygon(vertices, this.shared);
  60515. };
  60516. Polygon.prototype.flip = function () {
  60517. this.vertices.reverse().map(function (v) { v.flip(); });
  60518. this.plane.flip();
  60519. };
  60520. return Polygon;
  60521. }());
  60522. // # class Node
  60523. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  60524. // by picking a polygon to split along. That polygon (and all other coplanar
  60525. // polygons) are added directly to that node and the other polygons are added to
  60526. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  60527. // no distinction between internal and leaf nodes.
  60528. var Node = (function () {
  60529. function Node(polygons) {
  60530. this.plane = null;
  60531. this.front = null;
  60532. this.back = null;
  60533. this.polygons = [];
  60534. if (polygons) {
  60535. this.build(polygons);
  60536. }
  60537. }
  60538. Node.prototype.clone = function () {
  60539. var node = new Node();
  60540. node.plane = this.plane && this.plane.clone();
  60541. node.front = this.front && this.front.clone();
  60542. node.back = this.back && this.back.clone();
  60543. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  60544. return node;
  60545. };
  60546. // Convert solid space to empty space and empty space to solid space.
  60547. Node.prototype.invert = function () {
  60548. for (var i = 0; i < this.polygons.length; i++) {
  60549. this.polygons[i].flip();
  60550. }
  60551. if (this.plane) {
  60552. this.plane.flip();
  60553. }
  60554. if (this.front) {
  60555. this.front.invert();
  60556. }
  60557. if (this.back) {
  60558. this.back.invert();
  60559. }
  60560. var temp = this.front;
  60561. this.front = this.back;
  60562. this.back = temp;
  60563. };
  60564. // Recursively remove all polygons in `polygons` that are inside this BSP
  60565. // tree.
  60566. Node.prototype.clipPolygons = function (polygons) {
  60567. if (!this.plane)
  60568. return polygons.slice();
  60569. var front = [], back = [];
  60570. for (var i = 0; i < polygons.length; i++) {
  60571. this.plane.splitPolygon(polygons[i], front, back, front, back);
  60572. }
  60573. if (this.front) {
  60574. front = this.front.clipPolygons(front);
  60575. }
  60576. if (this.back) {
  60577. back = this.back.clipPolygons(back);
  60578. }
  60579. else {
  60580. back = [];
  60581. }
  60582. return front.concat(back);
  60583. };
  60584. // Remove all polygons in this BSP tree that are inside the other BSP tree
  60585. // `bsp`.
  60586. Node.prototype.clipTo = function (bsp) {
  60587. this.polygons = bsp.clipPolygons(this.polygons);
  60588. if (this.front)
  60589. this.front.clipTo(bsp);
  60590. if (this.back)
  60591. this.back.clipTo(bsp);
  60592. };
  60593. // Return a list of all polygons in this BSP tree.
  60594. Node.prototype.allPolygons = function () {
  60595. var polygons = this.polygons.slice();
  60596. if (this.front)
  60597. polygons = polygons.concat(this.front.allPolygons());
  60598. if (this.back)
  60599. polygons = polygons.concat(this.back.allPolygons());
  60600. return polygons;
  60601. };
  60602. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  60603. // new polygons are filtered down to the bottom of the tree and become new
  60604. // nodes there. Each set of polygons is partitioned using the first polygon
  60605. // (no heuristic is used to pick a good split).
  60606. Node.prototype.build = function (polygons) {
  60607. if (!polygons.length)
  60608. return;
  60609. if (!this.plane)
  60610. this.plane = polygons[0].plane.clone();
  60611. var front = [], back = [];
  60612. for (var i = 0; i < polygons.length; i++) {
  60613. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  60614. }
  60615. if (front.length) {
  60616. if (!this.front)
  60617. this.front = new Node();
  60618. this.front.build(front);
  60619. }
  60620. if (back.length) {
  60621. if (!this.back)
  60622. this.back = new Node();
  60623. this.back.build(back);
  60624. }
  60625. };
  60626. return Node;
  60627. }());
  60628. var CSG = (function () {
  60629. function CSG() {
  60630. this.polygons = new Array();
  60631. }
  60632. // Convert BABYLON.Mesh to BABYLON.CSG
  60633. CSG.FromMesh = function (mesh) {
  60634. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  60635. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  60636. if (mesh instanceof BABYLON.Mesh) {
  60637. mesh.computeWorldMatrix(true);
  60638. matrix = mesh.getWorldMatrix();
  60639. meshPosition = mesh.position.clone();
  60640. meshRotation = mesh.rotation.clone();
  60641. if (mesh.rotationQuaternion) {
  60642. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  60643. }
  60644. meshScaling = mesh.scaling.clone();
  60645. }
  60646. else {
  60647. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  60648. }
  60649. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60650. var subMeshes = mesh.subMeshes;
  60651. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  60652. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  60653. vertices = [];
  60654. for (var j = 0; j < 3; j++) {
  60655. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  60656. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  60657. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  60658. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  60659. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  60660. vertex = new Vertex(position, normal, uv);
  60661. vertices.push(vertex);
  60662. }
  60663. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  60664. // To handle the case of degenerated triangle
  60665. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  60666. if (polygon.plane)
  60667. polygons.push(polygon);
  60668. }
  60669. }
  60670. var csg = CSG.FromPolygons(polygons);
  60671. csg.matrix = matrix;
  60672. csg.position = meshPosition;
  60673. csg.rotation = meshRotation;
  60674. csg.scaling = meshScaling;
  60675. csg.rotationQuaternion = meshRotationQuaternion;
  60676. currentCSGMeshId++;
  60677. return csg;
  60678. };
  60679. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  60680. CSG.FromPolygons = function (polygons) {
  60681. var csg = new CSG();
  60682. csg.polygons = polygons;
  60683. return csg;
  60684. };
  60685. CSG.prototype.clone = function () {
  60686. var csg = new CSG();
  60687. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  60688. csg.copyTransformAttributes(this);
  60689. return csg;
  60690. };
  60691. CSG.prototype.toPolygons = function () {
  60692. return this.polygons;
  60693. };
  60694. CSG.prototype.union = function (csg) {
  60695. var a = new Node(this.clone().polygons);
  60696. var b = new Node(csg.clone().polygons);
  60697. a.clipTo(b);
  60698. b.clipTo(a);
  60699. b.invert();
  60700. b.clipTo(a);
  60701. b.invert();
  60702. a.build(b.allPolygons());
  60703. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60704. };
  60705. CSG.prototype.unionInPlace = function (csg) {
  60706. var a = new Node(this.polygons);
  60707. var b = new Node(csg.polygons);
  60708. a.clipTo(b);
  60709. b.clipTo(a);
  60710. b.invert();
  60711. b.clipTo(a);
  60712. b.invert();
  60713. a.build(b.allPolygons());
  60714. this.polygons = a.allPolygons();
  60715. };
  60716. CSG.prototype.subtract = function (csg) {
  60717. var a = new Node(this.clone().polygons);
  60718. var b = new Node(csg.clone().polygons);
  60719. a.invert();
  60720. a.clipTo(b);
  60721. b.clipTo(a);
  60722. b.invert();
  60723. b.clipTo(a);
  60724. b.invert();
  60725. a.build(b.allPolygons());
  60726. a.invert();
  60727. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60728. };
  60729. CSG.prototype.subtractInPlace = function (csg) {
  60730. var a = new Node(this.polygons);
  60731. var b = new Node(csg.polygons);
  60732. a.invert();
  60733. a.clipTo(b);
  60734. b.clipTo(a);
  60735. b.invert();
  60736. b.clipTo(a);
  60737. b.invert();
  60738. a.build(b.allPolygons());
  60739. a.invert();
  60740. this.polygons = a.allPolygons();
  60741. };
  60742. CSG.prototype.intersect = function (csg) {
  60743. var a = new Node(this.clone().polygons);
  60744. var b = new Node(csg.clone().polygons);
  60745. a.invert();
  60746. b.clipTo(a);
  60747. b.invert();
  60748. a.clipTo(b);
  60749. b.clipTo(a);
  60750. a.build(b.allPolygons());
  60751. a.invert();
  60752. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60753. };
  60754. CSG.prototype.intersectInPlace = function (csg) {
  60755. var a = new Node(this.polygons);
  60756. var b = new Node(csg.polygons);
  60757. a.invert();
  60758. b.clipTo(a);
  60759. b.invert();
  60760. a.clipTo(b);
  60761. b.clipTo(a);
  60762. a.build(b.allPolygons());
  60763. a.invert();
  60764. this.polygons = a.allPolygons();
  60765. };
  60766. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  60767. // not modified.
  60768. CSG.prototype.inverse = function () {
  60769. var csg = this.clone();
  60770. csg.inverseInPlace();
  60771. return csg;
  60772. };
  60773. CSG.prototype.inverseInPlace = function () {
  60774. this.polygons.map(function (p) { p.flip(); });
  60775. };
  60776. // This is used to keep meshes transformations so they can be restored
  60777. // when we build back a Babylon Mesh
  60778. // NB : All CSG operations are performed in world coordinates
  60779. CSG.prototype.copyTransformAttributes = function (csg) {
  60780. this.matrix = csg.matrix;
  60781. this.position = csg.position;
  60782. this.rotation = csg.rotation;
  60783. this.scaling = csg.scaling;
  60784. this.rotationQuaternion = csg.rotationQuaternion;
  60785. return this;
  60786. };
  60787. // Build Raw mesh from CSG
  60788. // Coordinates here are in world space
  60789. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  60790. var matrix = this.matrix.clone();
  60791. matrix.invert();
  60792. 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;
  60793. if (keepSubMeshes) {
  60794. // Sort Polygons, since subMeshes are indices range
  60795. polygons.sort(function (a, b) {
  60796. if (a.shared.meshId === b.shared.meshId) {
  60797. return a.shared.subMeshId - b.shared.subMeshId;
  60798. }
  60799. else {
  60800. return a.shared.meshId - b.shared.meshId;
  60801. }
  60802. });
  60803. }
  60804. for (var i = 0, il = polygons.length; i < il; i++) {
  60805. polygon = polygons[i];
  60806. // Building SubMeshes
  60807. if (!subMesh_dict[polygon.shared.meshId]) {
  60808. subMesh_dict[polygon.shared.meshId] = {};
  60809. }
  60810. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  60811. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  60812. indexStart: +Infinity,
  60813. indexEnd: -Infinity,
  60814. materialIndex: polygon.shared.materialIndex
  60815. };
  60816. }
  60817. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  60818. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  60819. polygonIndices[0] = 0;
  60820. polygonIndices[1] = j - 1;
  60821. polygonIndices[2] = j;
  60822. for (var k = 0; k < 3; k++) {
  60823. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  60824. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  60825. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  60826. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  60827. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  60828. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  60829. // Check if 2 points can be merged
  60830. if (!(typeof vertex_idx !== 'undefined' &&
  60831. normals[vertex_idx * 3] === localNormal.x &&
  60832. normals[vertex_idx * 3 + 1] === localNormal.y &&
  60833. normals[vertex_idx * 3 + 2] === localNormal.z &&
  60834. uvs[vertex_idx * 2] === uv.x &&
  60835. uvs[vertex_idx * 2 + 1] === uv.y)) {
  60836. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  60837. uvs.push(uv.x, uv.y);
  60838. normals.push(normal.x, normal.y, normal.z);
  60839. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  60840. }
  60841. indices.push(vertex_idx);
  60842. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  60843. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  60844. currentIndex++;
  60845. }
  60846. }
  60847. }
  60848. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  60849. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  60850. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  60851. mesh.setIndices(indices);
  60852. if (keepSubMeshes) {
  60853. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  60854. var materialIndexOffset = 0, materialMaxIndex;
  60855. mesh.subMeshes = new Array();
  60856. for (var m in subMesh_dict) {
  60857. materialMaxIndex = -1;
  60858. for (var sm in subMesh_dict[m]) {
  60859. subMesh_obj = subMesh_dict[m][sm];
  60860. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  60861. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  60862. }
  60863. materialIndexOffset += ++materialMaxIndex;
  60864. }
  60865. }
  60866. return mesh;
  60867. };
  60868. // Build Mesh from CSG taking material and transforms into account
  60869. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  60870. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  60871. mesh.material = material;
  60872. mesh.position.copyFrom(this.position);
  60873. mesh.rotation.copyFrom(this.rotation);
  60874. if (this.rotationQuaternion) {
  60875. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  60876. }
  60877. mesh.scaling.copyFrom(this.scaling);
  60878. mesh.computeWorldMatrix(true);
  60879. return mesh;
  60880. };
  60881. return CSG;
  60882. }());
  60883. BABYLON.CSG = CSG;
  60884. })(BABYLON || (BABYLON = {}));
  60885. //# sourceMappingURL=babylon.csg.js.map
  60886. var BABYLON;
  60887. (function (BABYLON) {
  60888. var LensFlare = (function () {
  60889. function LensFlare(size, position, color, imgUrl, system) {
  60890. this.size = size;
  60891. this.position = position;
  60892. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  60893. this.dispose = function () {
  60894. if (this.texture) {
  60895. this.texture.dispose();
  60896. }
  60897. // Remove from scene
  60898. var index = this._system.lensFlares.indexOf(this);
  60899. this._system.lensFlares.splice(index, 1);
  60900. };
  60901. this.color = color || new BABYLON.Color3(1, 1, 1);
  60902. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  60903. this._system = system;
  60904. system.lensFlares.push(this);
  60905. }
  60906. return LensFlare;
  60907. }());
  60908. BABYLON.LensFlare = LensFlare;
  60909. })(BABYLON || (BABYLON = {}));
  60910. //# sourceMappingURL=babylon.lensFlare.js.map
  60911. var BABYLON;
  60912. (function (BABYLON) {
  60913. var LensFlareSystem = (function () {
  60914. function LensFlareSystem(name, emitter, scene) {
  60915. this.name = name;
  60916. this.lensFlares = new Array();
  60917. this.borderLimit = 300;
  60918. this.viewportBorder = 0;
  60919. this.layerMask = 0x0FFFFFFF;
  60920. this._vertexBuffers = {};
  60921. this._isEnabled = true;
  60922. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60923. this._emitter = emitter;
  60924. this.id = name;
  60925. scene.lensFlareSystems.push(this);
  60926. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  60927. var engine = scene.getEngine();
  60928. // VBO
  60929. var vertices = [];
  60930. vertices.push(1, 1);
  60931. vertices.push(-1, 1);
  60932. vertices.push(-1, -1);
  60933. vertices.push(1, -1);
  60934. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60935. // Indices
  60936. var indices = [];
  60937. indices.push(0);
  60938. indices.push(1);
  60939. indices.push(2);
  60940. indices.push(0);
  60941. indices.push(2);
  60942. indices.push(3);
  60943. this._indexBuffer = engine.createIndexBuffer(indices);
  60944. // Effects
  60945. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  60946. }
  60947. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  60948. get: function () {
  60949. return this._isEnabled;
  60950. },
  60951. set: function (value) {
  60952. this._isEnabled = value;
  60953. },
  60954. enumerable: true,
  60955. configurable: true
  60956. });
  60957. LensFlareSystem.prototype.getScene = function () {
  60958. return this._scene;
  60959. };
  60960. LensFlareSystem.prototype.getEmitter = function () {
  60961. return this._emitter;
  60962. };
  60963. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  60964. this._emitter = newEmitter;
  60965. };
  60966. LensFlareSystem.prototype.getEmitterPosition = function () {
  60967. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  60968. };
  60969. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  60970. var position = this.getEmitterPosition();
  60971. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  60972. this._positionX = position.x;
  60973. this._positionY = position.y;
  60974. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  60975. if (this.viewportBorder > 0) {
  60976. globalViewport.x -= this.viewportBorder;
  60977. globalViewport.y -= this.viewportBorder;
  60978. globalViewport.width += this.viewportBorder * 2;
  60979. globalViewport.height += this.viewportBorder * 2;
  60980. position.x += this.viewportBorder;
  60981. position.y += this.viewportBorder;
  60982. this._positionX += this.viewportBorder;
  60983. this._positionY += this.viewportBorder;
  60984. }
  60985. if (position.z > 0) {
  60986. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  60987. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  60988. return true;
  60989. }
  60990. return true;
  60991. }
  60992. return false;
  60993. };
  60994. LensFlareSystem.prototype._isVisible = function () {
  60995. if (!this._isEnabled) {
  60996. return false;
  60997. }
  60998. var emitterPosition = this.getEmitterPosition();
  60999. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  61000. var distance = direction.length();
  61001. direction.normalize();
  61002. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  61003. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  61004. return !pickInfo.hit || pickInfo.distance > distance;
  61005. };
  61006. LensFlareSystem.prototype.render = function () {
  61007. if (!this._effect.isReady())
  61008. return false;
  61009. var engine = this._scene.getEngine();
  61010. var viewport = this._scene.activeCamera.viewport;
  61011. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  61012. // Position
  61013. if (!this.computeEffectivePosition(globalViewport)) {
  61014. return false;
  61015. }
  61016. // Visibility
  61017. if (!this._isVisible()) {
  61018. return false;
  61019. }
  61020. // Intensity
  61021. var awayX;
  61022. var awayY;
  61023. if (this._positionX < this.borderLimit + globalViewport.x) {
  61024. awayX = this.borderLimit + globalViewport.x - this._positionX;
  61025. }
  61026. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  61027. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  61028. }
  61029. else {
  61030. awayX = 0;
  61031. }
  61032. if (this._positionY < this.borderLimit + globalViewport.y) {
  61033. awayY = this.borderLimit + globalViewport.y - this._positionY;
  61034. }
  61035. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  61036. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  61037. }
  61038. else {
  61039. awayY = 0;
  61040. }
  61041. var away = (awayX > awayY) ? awayX : awayY;
  61042. away -= this.viewportBorder;
  61043. if (away > this.borderLimit) {
  61044. away = this.borderLimit;
  61045. }
  61046. var intensity = 1.0 - (away / this.borderLimit);
  61047. if (intensity < 0) {
  61048. return false;
  61049. }
  61050. if (intensity > 1.0) {
  61051. intensity = 1.0;
  61052. }
  61053. if (this.viewportBorder > 0) {
  61054. globalViewport.x += this.viewportBorder;
  61055. globalViewport.y += this.viewportBorder;
  61056. globalViewport.width -= this.viewportBorder * 2;
  61057. globalViewport.height -= this.viewportBorder * 2;
  61058. this._positionX -= this.viewportBorder;
  61059. this._positionY -= this.viewportBorder;
  61060. }
  61061. // Position
  61062. var centerX = globalViewport.x + globalViewport.width / 2;
  61063. var centerY = globalViewport.y + globalViewport.height / 2;
  61064. var distX = centerX - this._positionX;
  61065. var distY = centerY - this._positionY;
  61066. // Effects
  61067. engine.enableEffect(this._effect);
  61068. engine.setState(false);
  61069. engine.setDepthBuffer(false);
  61070. // VBOs
  61071. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  61072. // Flares
  61073. for (var index = 0; index < this.lensFlares.length; index++) {
  61074. var flare = this.lensFlares[index];
  61075. engine.setAlphaMode(flare.alphaMode);
  61076. var x = centerX - (distX * flare.position);
  61077. var y = centerY - (distY * flare.position);
  61078. var cw = flare.size;
  61079. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  61080. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  61081. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  61082. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  61083. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  61084. // Texture
  61085. this._effect.setTexture("textureSampler", flare.texture);
  61086. // Color
  61087. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  61088. // Draw order
  61089. engine.draw(true, 0, 6);
  61090. }
  61091. engine.setDepthBuffer(true);
  61092. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61093. return true;
  61094. };
  61095. LensFlareSystem.prototype.dispose = function () {
  61096. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61097. if (vertexBuffer) {
  61098. vertexBuffer.dispose();
  61099. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61100. }
  61101. if (this._indexBuffer) {
  61102. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61103. this._indexBuffer = null;
  61104. }
  61105. while (this.lensFlares.length) {
  61106. this.lensFlares[0].dispose();
  61107. }
  61108. // Remove from scene
  61109. var index = this._scene.lensFlareSystems.indexOf(this);
  61110. this._scene.lensFlareSystems.splice(index, 1);
  61111. };
  61112. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  61113. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  61114. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  61115. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  61116. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  61117. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  61118. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  61119. var parsedFlare = parsedLensFlareSystem.flares[index];
  61120. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  61121. }
  61122. return lensFlareSystem;
  61123. };
  61124. LensFlareSystem.prototype.serialize = function () {
  61125. var serializationObject = {};
  61126. serializationObject.id = this.id;
  61127. serializationObject.name = this.name;
  61128. serializationObject.emitterId = this.getEmitter().id;
  61129. serializationObject.borderLimit = this.borderLimit;
  61130. serializationObject.flares = [];
  61131. for (var index = 0; index < this.lensFlares.length; index++) {
  61132. var flare = this.lensFlares[index];
  61133. serializationObject.flares.push({
  61134. size: flare.size,
  61135. position: flare.position,
  61136. color: flare.color.asArray(),
  61137. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  61138. });
  61139. }
  61140. return serializationObject;
  61141. };
  61142. return LensFlareSystem;
  61143. }());
  61144. BABYLON.LensFlareSystem = LensFlareSystem;
  61145. })(BABYLON || (BABYLON = {}));
  61146. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  61147. var BABYLON;
  61148. (function (BABYLON) {
  61149. /**
  61150. * This is a holder class for the physics joint created by the physics plugin.
  61151. * It holds a set of functions to control the underlying joint.
  61152. */
  61153. var PhysicsJoint = (function () {
  61154. function PhysicsJoint(type, jointData) {
  61155. this.type = type;
  61156. this.jointData = jointData;
  61157. jointData.nativeParams = jointData.nativeParams || {};
  61158. }
  61159. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  61160. get: function () {
  61161. return this._physicsJoint;
  61162. },
  61163. set: function (newJoint) {
  61164. if (this._physicsJoint) {
  61165. //remove from the wolrd
  61166. }
  61167. this._physicsJoint = newJoint;
  61168. },
  61169. enumerable: true,
  61170. configurable: true
  61171. });
  61172. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  61173. set: function (physicsPlugin) {
  61174. this._physicsPlugin = physicsPlugin;
  61175. },
  61176. enumerable: true,
  61177. configurable: true
  61178. });
  61179. /**
  61180. * Execute a function that is physics-plugin specific.
  61181. * @param {Function} func the function that will be executed.
  61182. * It accepts two parameters: the physics world and the physics joint.
  61183. */
  61184. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  61185. func(this._physicsPlugin.world, this._physicsJoint);
  61186. };
  61187. //TODO check if the native joints are the same
  61188. //Joint Types
  61189. PhysicsJoint.DistanceJoint = 0;
  61190. PhysicsJoint.HingeJoint = 1;
  61191. PhysicsJoint.BallAndSocketJoint = 2;
  61192. PhysicsJoint.WheelJoint = 3;
  61193. PhysicsJoint.SliderJoint = 4;
  61194. //OIMO
  61195. PhysicsJoint.PrismaticJoint = 5;
  61196. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  61197. PhysicsJoint.UniversalJoint = 6;
  61198. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  61199. //Cannon
  61200. //Similar to a Ball-Joint. Different in params
  61201. PhysicsJoint.PointToPointJoint = 8;
  61202. //Cannon only at the moment
  61203. PhysicsJoint.SpringJoint = 9;
  61204. PhysicsJoint.LockJoint = 10;
  61205. return PhysicsJoint;
  61206. }());
  61207. BABYLON.PhysicsJoint = PhysicsJoint;
  61208. /**
  61209. * A class representing a physics distance joint.
  61210. */
  61211. var DistanceJoint = (function (_super) {
  61212. __extends(DistanceJoint, _super);
  61213. function DistanceJoint(jointData) {
  61214. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  61215. }
  61216. /**
  61217. * Update the predefined distance.
  61218. */
  61219. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  61220. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  61221. };
  61222. return DistanceJoint;
  61223. }(PhysicsJoint));
  61224. BABYLON.DistanceJoint = DistanceJoint;
  61225. var MotorEnabledJoint = (function (_super) {
  61226. __extends(MotorEnabledJoint, _super);
  61227. function MotorEnabledJoint(type, jointData) {
  61228. return _super.call(this, type, jointData) || this;
  61229. }
  61230. /**
  61231. * Set the motor values.
  61232. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61233. * @param {number} force the force to apply
  61234. * @param {number} maxForce max force for this motor.
  61235. */
  61236. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  61237. this._physicsPlugin.setMotor(this, force, maxForce);
  61238. };
  61239. /**
  61240. * Set the motor's limits.
  61241. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61242. */
  61243. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  61244. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  61245. };
  61246. return MotorEnabledJoint;
  61247. }(PhysicsJoint));
  61248. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  61249. /**
  61250. * This class represents a single hinge physics joint
  61251. */
  61252. var HingeJoint = (function (_super) {
  61253. __extends(HingeJoint, _super);
  61254. function HingeJoint(jointData) {
  61255. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  61256. }
  61257. /**
  61258. * Set the motor values.
  61259. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61260. * @param {number} force the force to apply
  61261. * @param {number} maxForce max force for this motor.
  61262. */
  61263. HingeJoint.prototype.setMotor = function (force, maxForce) {
  61264. this._physicsPlugin.setMotor(this, force, maxForce);
  61265. };
  61266. /**
  61267. * Set the motor's limits.
  61268. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61269. */
  61270. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  61271. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  61272. };
  61273. return HingeJoint;
  61274. }(MotorEnabledJoint));
  61275. BABYLON.HingeJoint = HingeJoint;
  61276. /**
  61277. * This class represents a dual hinge physics joint (same as wheel joint)
  61278. */
  61279. var Hinge2Joint = (function (_super) {
  61280. __extends(Hinge2Joint, _super);
  61281. function Hinge2Joint(jointData) {
  61282. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  61283. }
  61284. /**
  61285. * Set the motor values.
  61286. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61287. * @param {number} force the force to apply
  61288. * @param {number} maxForce max force for this motor.
  61289. * @param {motorIndex} the motor's index, 0 or 1.
  61290. */
  61291. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  61292. if (motorIndex === void 0) { motorIndex = 0; }
  61293. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  61294. };
  61295. /**
  61296. * Set the motor limits.
  61297. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61298. * @param {number} upperLimit the upper limit
  61299. * @param {number} lowerLimit lower limit
  61300. * @param {motorIndex} the motor's index, 0 or 1.
  61301. */
  61302. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  61303. if (motorIndex === void 0) { motorIndex = 0; }
  61304. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  61305. };
  61306. return Hinge2Joint;
  61307. }(MotorEnabledJoint));
  61308. BABYLON.Hinge2Joint = Hinge2Joint;
  61309. })(BABYLON || (BABYLON = {}));
  61310. //# sourceMappingURL=babylon.physicsJoint.js.map
  61311. var BABYLON;
  61312. (function (BABYLON) {
  61313. var PhysicsImpostor = (function () {
  61314. function PhysicsImpostor(object, type, _options, _scene) {
  61315. if (_options === void 0) { _options = { mass: 0 }; }
  61316. var _this = this;
  61317. this.object = object;
  61318. this.type = type;
  61319. this._options = _options;
  61320. this._scene = _scene;
  61321. this._bodyUpdateRequired = false;
  61322. this._onBeforePhysicsStepCallbacks = new Array();
  61323. this._onAfterPhysicsStepCallbacks = new Array();
  61324. this._onPhysicsCollideCallbacks = [];
  61325. this._deltaPosition = BABYLON.Vector3.Zero();
  61326. this._isDisposed = false;
  61327. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  61328. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  61329. /**
  61330. * this function is executed by the physics engine.
  61331. */
  61332. this.beforeStep = function () {
  61333. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  61334. //conjugate deltaRotation
  61335. if (_this._deltaRotationConjugated) {
  61336. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  61337. }
  61338. else {
  61339. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  61340. }
  61341. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  61342. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  61343. func(_this);
  61344. });
  61345. };
  61346. /**
  61347. * this function is executed by the physics engine.
  61348. */
  61349. this.afterStep = function () {
  61350. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  61351. func(_this);
  61352. });
  61353. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  61354. _this.object.position.addInPlace(_this._deltaPosition);
  61355. if (_this._deltaRotation) {
  61356. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  61357. }
  61358. };
  61359. /**
  61360. * Legacy collision detection event support
  61361. */
  61362. this.onCollideEvent = null;
  61363. //event and body object due to cannon's event-based architecture.
  61364. this.onCollide = function (e) {
  61365. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  61366. return;
  61367. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  61368. if (otherImpostor) {
  61369. // Legacy collision detection event support
  61370. if (_this.onCollideEvent) {
  61371. _this.onCollideEvent(_this, otherImpostor);
  61372. }
  61373. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  61374. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  61375. }).forEach(function (obj) {
  61376. obj.callback(_this, otherImpostor);
  61377. });
  61378. }
  61379. };
  61380. //sanity check!
  61381. if (!this.object) {
  61382. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  61383. return;
  61384. }
  61385. //legacy support for old syntax.
  61386. if (!this._scene && object.getScene) {
  61387. this._scene = object.getScene();
  61388. }
  61389. this._physicsEngine = this._scene.getPhysicsEngine();
  61390. if (!this._physicsEngine) {
  61391. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  61392. }
  61393. else {
  61394. //set the object's quaternion, if not set
  61395. if (!this.object.rotationQuaternion) {
  61396. if (this.object.rotation) {
  61397. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  61398. }
  61399. else {
  61400. this.object.rotationQuaternion = new BABYLON.Quaternion();
  61401. }
  61402. }
  61403. //default options params
  61404. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  61405. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  61406. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  61407. this._joints = [];
  61408. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  61409. if (!this.object.parent) {
  61410. this._init();
  61411. }
  61412. else if (this.object.parent.physicsImpostor) {
  61413. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  61414. }
  61415. }
  61416. }
  61417. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  61418. get: function () {
  61419. return this._isDisposed;
  61420. },
  61421. enumerable: true,
  61422. configurable: true
  61423. });
  61424. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  61425. get: function () {
  61426. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  61427. },
  61428. set: function (value) {
  61429. this.setMass(value);
  61430. },
  61431. enumerable: true,
  61432. configurable: true
  61433. });
  61434. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  61435. get: function () {
  61436. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  61437. },
  61438. set: function (value) {
  61439. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  61440. },
  61441. enumerable: true,
  61442. configurable: true
  61443. });
  61444. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  61445. get: function () {
  61446. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  61447. },
  61448. set: function (value) {
  61449. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  61450. },
  61451. enumerable: true,
  61452. configurable: true
  61453. });
  61454. /**
  61455. * This function will completly initialize this impostor.
  61456. * It will create a new body - but only if this mesh has no parent.
  61457. * If it has, this impostor will not be used other than to define the impostor
  61458. * of the child mesh.
  61459. */
  61460. PhysicsImpostor.prototype._init = function () {
  61461. this._physicsEngine.removeImpostor(this);
  61462. this.physicsBody = null;
  61463. this._parent = this._parent || this._getPhysicsParent();
  61464. if (!this.parent) {
  61465. this._physicsEngine.addImpostor(this);
  61466. }
  61467. };
  61468. PhysicsImpostor.prototype._getPhysicsParent = function () {
  61469. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  61470. var parentMesh = this.object.parent;
  61471. return parentMesh.physicsImpostor;
  61472. }
  61473. return;
  61474. };
  61475. /**
  61476. * Should a new body be generated.
  61477. */
  61478. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  61479. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  61480. };
  61481. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  61482. this.forceUpdate();
  61483. };
  61484. /**
  61485. * Force a regeneration of this or the parent's impostor's body.
  61486. * Use under cautious - This will remove all joints already implemented.
  61487. */
  61488. PhysicsImpostor.prototype.forceUpdate = function () {
  61489. this._init();
  61490. if (this.parent) {
  61491. this.parent.forceUpdate();
  61492. }
  61493. };
  61494. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  61495. /*public get mesh(): AbstractMesh {
  61496. return this._mesh;
  61497. }*/
  61498. /**
  61499. * Gets the body that holds this impostor. Either its own, or its parent.
  61500. */
  61501. get: function () {
  61502. return this._parent ? this._parent.physicsBody : this._physicsBody;
  61503. },
  61504. /**
  61505. * Set the physics body. Used mainly by the physics engine/plugin
  61506. */
  61507. set: function (physicsBody) {
  61508. if (this._physicsBody) {
  61509. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  61510. }
  61511. this._physicsBody = physicsBody;
  61512. this.resetUpdateFlags();
  61513. },
  61514. enumerable: true,
  61515. configurable: true
  61516. });
  61517. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  61518. get: function () {
  61519. return this._parent;
  61520. },
  61521. set: function (value) {
  61522. this._parent = value;
  61523. },
  61524. enumerable: true,
  61525. configurable: true
  61526. });
  61527. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  61528. this._bodyUpdateRequired = false;
  61529. };
  61530. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  61531. if (this.object.getBoundingInfo) {
  61532. var q = this.object.rotationQuaternion;
  61533. //reset rotation
  61534. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  61535. //calculate the world matrix with no rotation
  61536. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61537. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  61538. //bring back the rotation
  61539. this.object.rotationQuaternion = q;
  61540. //calculate the world matrix with the new rotation
  61541. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61542. return size;
  61543. }
  61544. else {
  61545. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  61546. }
  61547. };
  61548. PhysicsImpostor.prototype.getObjectCenter = function () {
  61549. if (this.object.getBoundingInfo) {
  61550. return this.object.getBoundingInfo().boundingBox.centerWorld;
  61551. }
  61552. else {
  61553. return this.object.position;
  61554. }
  61555. };
  61556. /**
  61557. * Get a specific parametes from the options parameter.
  61558. */
  61559. PhysicsImpostor.prototype.getParam = function (paramName) {
  61560. return this._options[paramName];
  61561. };
  61562. /**
  61563. * Sets a specific parameter in the options given to the physics plugin
  61564. */
  61565. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  61566. this._options[paramName] = value;
  61567. this._bodyUpdateRequired = true;
  61568. };
  61569. /**
  61570. * Specifically change the body's mass option. Won't recreate the physics body object
  61571. */
  61572. PhysicsImpostor.prototype.setMass = function (mass) {
  61573. if (this.getParam("mass") !== mass) {
  61574. this.setParam("mass", mass);
  61575. }
  61576. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  61577. };
  61578. PhysicsImpostor.prototype.getLinearVelocity = function () {
  61579. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  61580. };
  61581. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  61582. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  61583. };
  61584. PhysicsImpostor.prototype.getAngularVelocity = function () {
  61585. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  61586. };
  61587. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  61588. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  61589. };
  61590. /**
  61591. * Execute a function with the physics plugin native code.
  61592. * Provide a function the will have two variables - the world object and the physics body object.
  61593. */
  61594. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  61595. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  61596. };
  61597. /**
  61598. * Register a function that will be executed before the physics world is stepping forward.
  61599. */
  61600. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  61601. this._onBeforePhysicsStepCallbacks.push(func);
  61602. };
  61603. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  61604. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  61605. if (index > -1) {
  61606. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  61607. }
  61608. else {
  61609. BABYLON.Tools.Warn("Function to remove was not found");
  61610. }
  61611. };
  61612. /**
  61613. * Register a function that will be executed after the physics step
  61614. */
  61615. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  61616. this._onAfterPhysicsStepCallbacks.push(func);
  61617. };
  61618. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  61619. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  61620. if (index > -1) {
  61621. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  61622. }
  61623. else {
  61624. BABYLON.Tools.Warn("Function to remove was not found");
  61625. }
  61626. };
  61627. /**
  61628. * register a function that will be executed when this impostor collides against a different body.
  61629. */
  61630. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  61631. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  61632. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  61633. };
  61634. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  61635. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  61636. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  61637. if (index > -1) {
  61638. this._onPhysicsCollideCallbacks.splice(index, 1);
  61639. }
  61640. else {
  61641. BABYLON.Tools.Warn("Function to remove was not found");
  61642. }
  61643. };
  61644. /**
  61645. * Apply a force
  61646. */
  61647. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  61648. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  61649. };
  61650. /**
  61651. * Apply an impulse
  61652. */
  61653. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  61654. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  61655. };
  61656. /**
  61657. * A help function to create a joint.
  61658. */
  61659. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  61660. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  61661. this.addJoint(otherImpostor, joint);
  61662. };
  61663. /**
  61664. * Add a joint to this impostor with a different impostor.
  61665. */
  61666. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  61667. this._joints.push({
  61668. otherImpostor: otherImpostor,
  61669. joint: joint
  61670. });
  61671. this._physicsEngine.addJoint(this, otherImpostor, joint);
  61672. };
  61673. /**
  61674. * Will keep this body still, in a sleep mode.
  61675. */
  61676. PhysicsImpostor.prototype.sleep = function () {
  61677. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  61678. };
  61679. /**
  61680. * Wake the body up.
  61681. */
  61682. PhysicsImpostor.prototype.wakeUp = function () {
  61683. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  61684. };
  61685. PhysicsImpostor.prototype.clone = function (newObject) {
  61686. if (!newObject)
  61687. return null;
  61688. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  61689. };
  61690. PhysicsImpostor.prototype.dispose = function () {
  61691. var _this = this;
  61692. //no dispose if no physics engine is available.
  61693. if (!this._physicsEngine) {
  61694. return;
  61695. }
  61696. this._joints.forEach(function (j) {
  61697. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  61698. });
  61699. //dispose the physics body
  61700. this._physicsEngine.removeImpostor(this);
  61701. if (this.parent) {
  61702. this.parent.forceUpdate();
  61703. }
  61704. else {
  61705. /*this._object.getChildMeshes().forEach(function(mesh) {
  61706. if (mesh.physicsImpostor) {
  61707. if (disposeChildren) {
  61708. mesh.physicsImpostor.dispose();
  61709. mesh.physicsImpostor = null;
  61710. }
  61711. }
  61712. })*/
  61713. }
  61714. this._isDisposed = true;
  61715. };
  61716. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  61717. this._deltaPosition.copyFrom(position);
  61718. };
  61719. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  61720. if (!this._deltaRotation) {
  61721. this._deltaRotation = new BABYLON.Quaternion();
  61722. }
  61723. this._deltaRotation.copyFrom(rotation);
  61724. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  61725. };
  61726. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  61727. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  61728. };
  61729. PhysicsImpostor.prototype.getRadius = function () {
  61730. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  61731. };
  61732. /**
  61733. * Sync a bone with this impostor
  61734. * @param bone The bone to sync to the impostor.
  61735. * @param boneMesh The mesh that the bone is influencing.
  61736. * @param jointPivot The pivot of the joint / bone in local space.
  61737. * @param distToJoint Optional distance from the impostor to the joint.
  61738. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  61739. */
  61740. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  61741. var tempVec = PhysicsImpostor._tmpVecs[0];
  61742. var mesh = this.object;
  61743. if (adjustRotation) {
  61744. var tempQuat = PhysicsImpostor._tmpQuat;
  61745. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  61746. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  61747. }
  61748. else {
  61749. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  61750. }
  61751. tempVec.x = 0;
  61752. tempVec.y = 0;
  61753. tempVec.z = 0;
  61754. if (jointPivot) {
  61755. tempVec.x = jointPivot.x;
  61756. tempVec.y = jointPivot.y;
  61757. tempVec.z = jointPivot.z;
  61758. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  61759. if (distToJoint === undefined || distToJoint === null) {
  61760. distToJoint = jointPivot.length();
  61761. }
  61762. tempVec.x *= distToJoint;
  61763. tempVec.y *= distToJoint;
  61764. tempVec.z *= distToJoint;
  61765. }
  61766. if (bone.getParent()) {
  61767. tempVec.addInPlace(mesh.getAbsolutePosition());
  61768. bone.setAbsolutePosition(tempVec, boneMesh);
  61769. }
  61770. else {
  61771. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  61772. boneMesh.position.x -= tempVec.x;
  61773. boneMesh.position.y -= tempVec.y;
  61774. boneMesh.position.z -= tempVec.z;
  61775. }
  61776. };
  61777. /**
  61778. * Sync impostor to a bone
  61779. * @param bone The bone that the impostor will be synced to.
  61780. * @param boneMesh The mesh that the bone is influencing.
  61781. * @param jointPivot The pivot of the joint / bone in local space.
  61782. * @param distToJoint Optional distance from the impostor to the joint.
  61783. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  61784. * @param boneAxis Optional vector3 axis the bone is aligned with
  61785. */
  61786. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  61787. var mesh = this.object;
  61788. if (adjustRotation) {
  61789. var tempQuat = PhysicsImpostor._tmpQuat;
  61790. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  61791. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  61792. }
  61793. else {
  61794. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  61795. }
  61796. var pos = PhysicsImpostor._tmpVecs[0];
  61797. var boneDir = PhysicsImpostor._tmpVecs[1];
  61798. if (!boneAxis) {
  61799. boneAxis = PhysicsImpostor._tmpVecs[2];
  61800. boneAxis.x = 0;
  61801. boneAxis.y = 1;
  61802. boneAxis.z = 0;
  61803. }
  61804. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  61805. bone.getAbsolutePositionToRef(boneMesh, pos);
  61806. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  61807. distToJoint = jointPivot.length();
  61808. }
  61809. if (distToJoint !== undefined && distToJoint !== null) {
  61810. pos.x += boneDir.x * distToJoint;
  61811. pos.y += boneDir.y * distToJoint;
  61812. pos.z += boneDir.z * distToJoint;
  61813. }
  61814. mesh.setAbsolutePosition(pos);
  61815. };
  61816. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  61817. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  61818. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61819. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  61820. //Impostor types
  61821. PhysicsImpostor.NoImpostor = 0;
  61822. PhysicsImpostor.SphereImpostor = 1;
  61823. PhysicsImpostor.BoxImpostor = 2;
  61824. PhysicsImpostor.PlaneImpostor = 3;
  61825. PhysicsImpostor.MeshImpostor = 4;
  61826. PhysicsImpostor.CylinderImpostor = 7;
  61827. PhysicsImpostor.ParticleImpostor = 8;
  61828. PhysicsImpostor.HeightmapImpostor = 9;
  61829. return PhysicsImpostor;
  61830. }());
  61831. BABYLON.PhysicsImpostor = PhysicsImpostor;
  61832. })(BABYLON || (BABYLON = {}));
  61833. //# sourceMappingURL=babylon.physicsImpostor.js.map
  61834. var BABYLON;
  61835. (function (BABYLON) {
  61836. var PhysicsEngine = (function () {
  61837. function PhysicsEngine(gravity, _physicsPlugin) {
  61838. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  61839. this._physicsPlugin = _physicsPlugin;
  61840. //new methods and parameters
  61841. this._impostors = [];
  61842. this._joints = [];
  61843. if (!this._physicsPlugin.isSupported()) {
  61844. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  61845. + "Please make sure it is included.");
  61846. }
  61847. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  61848. this.setGravity(gravity);
  61849. this.setTimeStep();
  61850. }
  61851. PhysicsEngine.prototype.setGravity = function (gravity) {
  61852. this.gravity = gravity;
  61853. this._physicsPlugin.setGravity(this.gravity);
  61854. };
  61855. /**
  61856. * Set the time step of the physics engine.
  61857. * default is 1/60.
  61858. * To slow it down, enter 1/600 for example.
  61859. * To speed it up, 1/30
  61860. * @param {number} newTimeStep the new timestep to apply to this world.
  61861. */
  61862. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  61863. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  61864. this._physicsPlugin.setTimeStep(newTimeStep);
  61865. };
  61866. /**
  61867. * Get the time step of the physics engine.
  61868. */
  61869. PhysicsEngine.prototype.getTimeStep = function () {
  61870. return this._physicsPlugin.getTimeStep();
  61871. };
  61872. PhysicsEngine.prototype.dispose = function () {
  61873. this._impostors.forEach(function (impostor) {
  61874. impostor.dispose();
  61875. });
  61876. this._physicsPlugin.dispose();
  61877. };
  61878. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  61879. return this._physicsPlugin.name;
  61880. };
  61881. /**
  61882. * Adding a new impostor for the impostor tracking.
  61883. * This will be done by the impostor itself.
  61884. * @param {PhysicsImpostor} impostor the impostor to add
  61885. */
  61886. PhysicsEngine.prototype.addImpostor = function (impostor) {
  61887. impostor.uniqueId = this._impostors.push(impostor);
  61888. //if no parent, generate the body
  61889. if (!impostor.parent) {
  61890. this._physicsPlugin.generatePhysicsBody(impostor);
  61891. }
  61892. };
  61893. /**
  61894. * Remove an impostor from the engine.
  61895. * This impostor and its mesh will not longer be updated by the physics engine.
  61896. * @param {PhysicsImpostor} impostor the impostor to remove
  61897. */
  61898. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  61899. var index = this._impostors.indexOf(impostor);
  61900. if (index > -1) {
  61901. var removed = this._impostors.splice(index, 1);
  61902. //Is it needed?
  61903. if (removed.length) {
  61904. //this will also remove it from the world.
  61905. removed[0].physicsBody = null;
  61906. }
  61907. }
  61908. };
  61909. /**
  61910. * Add a joint to the physics engine
  61911. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  61912. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  61913. * @param {PhysicsJoint} the joint that will connect both impostors.
  61914. */
  61915. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  61916. var impostorJoint = {
  61917. mainImpostor: mainImpostor,
  61918. connectedImpostor: connectedImpostor,
  61919. joint: joint
  61920. };
  61921. joint.physicsPlugin = this._physicsPlugin;
  61922. this._joints.push(impostorJoint);
  61923. this._physicsPlugin.generateJoint(impostorJoint);
  61924. };
  61925. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  61926. var matchingJoints = this._joints.filter(function (impostorJoint) {
  61927. return (impostorJoint.connectedImpostor === connectedImpostor
  61928. && impostorJoint.joint === joint
  61929. && impostorJoint.mainImpostor === mainImpostor);
  61930. });
  61931. if (matchingJoints.length) {
  61932. this._physicsPlugin.removeJoint(matchingJoints[0]);
  61933. //TODO remove it from the list as well
  61934. }
  61935. };
  61936. /**
  61937. * Called by the scene. no need to call it.
  61938. */
  61939. PhysicsEngine.prototype._step = function (delta) {
  61940. var _this = this;
  61941. //check if any mesh has no body / requires an update
  61942. this._impostors.forEach(function (impostor) {
  61943. if (impostor.isBodyInitRequired()) {
  61944. _this._physicsPlugin.generatePhysicsBody(impostor);
  61945. }
  61946. });
  61947. if (delta > 0.1) {
  61948. delta = 0.1;
  61949. }
  61950. else if (delta <= 0) {
  61951. delta = 1.0 / 60.0;
  61952. }
  61953. this._physicsPlugin.executeStep(delta, this._impostors);
  61954. };
  61955. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  61956. return this._physicsPlugin;
  61957. };
  61958. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  61959. for (var i = 0; i < this._impostors.length; ++i) {
  61960. if (this._impostors[i].object === object) {
  61961. return this._impostors[i];
  61962. }
  61963. }
  61964. };
  61965. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  61966. for (var i = 0; i < this._impostors.length; ++i) {
  61967. if (this._impostors[i].physicsBody === body) {
  61968. return this._impostors[i];
  61969. }
  61970. }
  61971. };
  61972. // Statics
  61973. PhysicsEngine.Epsilon = 0.001;
  61974. return PhysicsEngine;
  61975. }());
  61976. BABYLON.PhysicsEngine = PhysicsEngine;
  61977. })(BABYLON || (BABYLON = {}));
  61978. //# sourceMappingURL=babylon.physicsEngine.js.map
  61979. var BABYLON;
  61980. (function (BABYLON) {
  61981. var CannonJSPlugin = (function () {
  61982. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  61983. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  61984. if (iterations === void 0) { iterations = 10; }
  61985. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  61986. this.name = "CannonJSPlugin";
  61987. this._physicsMaterials = [];
  61988. this._fixedTimeStep = 1 / 60;
  61989. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  61990. this._currentCollisionGroup = 2;
  61991. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  61992. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  61993. this._tmpPosition = BABYLON.Vector3.Zero();
  61994. this._tmpQuaternion = new BABYLON.Quaternion();
  61995. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  61996. this._tmpDeltaRotation = new BABYLON.Quaternion();
  61997. this._tmpUnityRotation = new BABYLON.Quaternion();
  61998. if (!this.isSupported()) {
  61999. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  62000. return;
  62001. }
  62002. this.world = new CANNON.World();
  62003. this.world.broadphase = new CANNON.NaiveBroadphase();
  62004. this.world.solver.iterations = iterations;
  62005. }
  62006. CannonJSPlugin.prototype.setGravity = function (gravity) {
  62007. this.world.gravity.copy(gravity);
  62008. };
  62009. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  62010. this._fixedTimeStep = timeStep;
  62011. };
  62012. CannonJSPlugin.prototype.getTimeStep = function () {
  62013. return this._fixedTimeStep;
  62014. };
  62015. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  62016. // Delta is in seconds, should be provided in milliseconds
  62017. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  62018. };
  62019. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  62020. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  62021. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  62022. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  62023. };
  62024. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  62025. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  62026. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  62027. impostor.physicsBody.applyForce(impulse, worldPoint);
  62028. };
  62029. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  62030. //parent-child relationship. Does this impostor has a parent impostor?
  62031. if (impostor.parent) {
  62032. if (impostor.physicsBody) {
  62033. this.removePhysicsBody(impostor);
  62034. //TODO is that needed?
  62035. impostor.forceUpdate();
  62036. }
  62037. return;
  62038. }
  62039. //should a new body be created for this impostor?
  62040. if (impostor.isBodyInitRequired()) {
  62041. var shape = this._createShape(impostor);
  62042. //unregister events, if body is being changed
  62043. var oldBody = impostor.physicsBody;
  62044. if (oldBody) {
  62045. this.removePhysicsBody(impostor);
  62046. }
  62047. //create the body and material
  62048. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  62049. var bodyCreationObject = {
  62050. mass: impostor.getParam("mass"),
  62051. material: material
  62052. };
  62053. // A simple extend, in case native options were used.
  62054. var nativeOptions = impostor.getParam("nativeOptions");
  62055. for (var key in nativeOptions) {
  62056. if (nativeOptions.hasOwnProperty(key)) {
  62057. bodyCreationObject[key] = nativeOptions[key];
  62058. }
  62059. }
  62060. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  62061. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  62062. this.world.addEventListener("preStep", impostor.beforeStep);
  62063. this.world.addEventListener("postStep", impostor.afterStep);
  62064. impostor.physicsBody.addShape(shape);
  62065. this.world.add(impostor.physicsBody);
  62066. //try to keep the body moving in the right direction by taking old properties.
  62067. //Should be tested!
  62068. if (oldBody) {
  62069. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  62070. impostor.physicsBody[param].copy(oldBody[param]);
  62071. });
  62072. }
  62073. this._processChildMeshes(impostor);
  62074. }
  62075. //now update the body's transformation
  62076. this._updatePhysicsBodyTransformation(impostor);
  62077. };
  62078. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  62079. var _this = this;
  62080. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  62081. if (meshChildren.length) {
  62082. var processMesh = function (localPosition, mesh) {
  62083. var childImpostor = mesh.getPhysicsImpostor();
  62084. if (childImpostor) {
  62085. var parent = childImpostor.parent;
  62086. if (parent !== mainImpostor) {
  62087. var localPosition = mesh.position;
  62088. if (childImpostor.physicsBody) {
  62089. _this.removePhysicsBody(childImpostor);
  62090. childImpostor.physicsBody = null;
  62091. }
  62092. childImpostor.parent = mainImpostor;
  62093. childImpostor.resetUpdateFlags();
  62094. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  62095. //Add the mass of the children.
  62096. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  62097. }
  62098. }
  62099. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  62100. };
  62101. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  62102. }
  62103. };
  62104. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  62105. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  62106. this.world.removeEventListener("preStep", impostor.beforeStep);
  62107. this.world.removeEventListener("postStep", impostor.afterStep);
  62108. this.world.remove(impostor.physicsBody);
  62109. };
  62110. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  62111. var mainBody = impostorJoint.mainImpostor.physicsBody;
  62112. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  62113. if (!mainBody || !connectedBody) {
  62114. return;
  62115. }
  62116. var constraint;
  62117. var jointData = impostorJoint.joint.jointData;
  62118. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  62119. var constraintData = {
  62120. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  62121. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  62122. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  62123. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  62124. maxForce: jointData.nativeParams.maxForce,
  62125. collideConnected: !!jointData.collision
  62126. };
  62127. switch (impostorJoint.joint.type) {
  62128. case BABYLON.PhysicsJoint.HingeJoint:
  62129. case BABYLON.PhysicsJoint.Hinge2Joint:
  62130. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  62131. break;
  62132. case BABYLON.PhysicsJoint.DistanceJoint:
  62133. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  62134. break;
  62135. case BABYLON.PhysicsJoint.SpringJoint:
  62136. var springData = jointData;
  62137. constraint = new CANNON.Spring(mainBody, connectedBody, {
  62138. restLength: springData.length,
  62139. stiffness: springData.stiffness,
  62140. damping: springData.damping,
  62141. localAnchorA: constraintData.pivotA,
  62142. localAnchorB: constraintData.pivotB
  62143. });
  62144. break;
  62145. case BABYLON.PhysicsJoint.LockJoint:
  62146. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  62147. break;
  62148. case BABYLON.PhysicsJoint.PointToPointJoint:
  62149. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  62150. default:
  62151. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  62152. break;
  62153. }
  62154. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  62155. constraint.collideConnected = !!jointData.collision;
  62156. impostorJoint.joint.physicsJoint = constraint;
  62157. //don't add spring as constraint, as it is not one.
  62158. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  62159. this.world.addConstraint(constraint);
  62160. }
  62161. else {
  62162. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  62163. constraint.applyForce();
  62164. });
  62165. }
  62166. };
  62167. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  62168. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  62169. };
  62170. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  62171. var index;
  62172. var mat;
  62173. for (index = 0; index < this._physicsMaterials.length; index++) {
  62174. mat = this._physicsMaterials[index];
  62175. if (mat.friction === friction && mat.restitution === restitution) {
  62176. return mat;
  62177. }
  62178. }
  62179. var currentMat = new CANNON.Material(name);
  62180. currentMat.friction = friction;
  62181. currentMat.restitution = restitution;
  62182. this._physicsMaterials.push(currentMat);
  62183. return currentMat;
  62184. };
  62185. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  62186. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  62187. };
  62188. CannonJSPlugin.prototype._createShape = function (impostor) {
  62189. var object = impostor.object;
  62190. var returnValue;
  62191. var extendSize = impostor.getObjectExtendSize();
  62192. switch (impostor.type) {
  62193. case BABYLON.PhysicsImpostor.SphereImpostor:
  62194. var radiusX = extendSize.x;
  62195. var radiusY = extendSize.y;
  62196. var radiusZ = extendSize.z;
  62197. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  62198. break;
  62199. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  62200. case BABYLON.PhysicsImpostor.CylinderImpostor:
  62201. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  62202. break;
  62203. case BABYLON.PhysicsImpostor.BoxImpostor:
  62204. var box = extendSize.scale(0.5);
  62205. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  62206. break;
  62207. case BABYLON.PhysicsImpostor.PlaneImpostor:
  62208. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  62209. returnValue = new CANNON.Plane();
  62210. break;
  62211. case BABYLON.PhysicsImpostor.MeshImpostor:
  62212. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  62213. var rawFaces = object.getIndices ? object.getIndices() : [];
  62214. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  62215. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  62216. break;
  62217. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  62218. returnValue = this._createHeightmap(object);
  62219. break;
  62220. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62221. returnValue = new CANNON.Particle();
  62222. break;
  62223. }
  62224. return returnValue;
  62225. };
  62226. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  62227. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62228. var matrix = [];
  62229. //For now pointDepth will not be used and will be automatically calculated.
  62230. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  62231. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  62232. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  62233. var elementSize = dim * 2 / arraySize;
  62234. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  62235. for (var i = 0; i < pos.length; i = i + 3) {
  62236. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  62237. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  62238. var y = pos[i + 1] + minY;
  62239. if (!matrix[x]) {
  62240. matrix[x] = [];
  62241. }
  62242. if (!matrix[x][z]) {
  62243. matrix[x][z] = y;
  62244. }
  62245. matrix[x][z] = Math.max(y, matrix[x][z]);
  62246. }
  62247. for (var x = 0; x <= arraySize; ++x) {
  62248. if (!matrix[x]) {
  62249. var loc = 1;
  62250. while (!matrix[(x + loc) % arraySize]) {
  62251. loc++;
  62252. }
  62253. matrix[x] = matrix[(x + loc) % arraySize].slice();
  62254. //console.log("missing x", x);
  62255. }
  62256. for (var z = 0; z <= arraySize; ++z) {
  62257. if (!matrix[x][z]) {
  62258. var loc = 1;
  62259. var newValue;
  62260. while (newValue === undefined) {
  62261. newValue = matrix[x][(z + loc++) % arraySize];
  62262. }
  62263. matrix[x][z] = newValue;
  62264. }
  62265. }
  62266. }
  62267. var shape = new CANNON.Heightfield(matrix, {
  62268. elementSize: elementSize
  62269. });
  62270. //For future reference, needed for body transformation
  62271. shape.minY = minY;
  62272. return shape;
  62273. };
  62274. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  62275. var object = impostor.object;
  62276. //make sure it is updated...
  62277. object.computeWorldMatrix && object.computeWorldMatrix(true);
  62278. // The delta between the mesh position and the mesh bounding box center
  62279. var center = impostor.getObjectCenter();
  62280. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  62281. this._tmpPosition.copyFrom(center);
  62282. var quaternion = object.rotationQuaternion;
  62283. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  62284. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  62285. //-90 DEG in X, precalculated
  62286. quaternion = quaternion.multiply(this._minus90X);
  62287. //Invert! (Precalculated, 90 deg in X)
  62288. //No need to clone. this will never change.
  62289. impostor.setDeltaRotation(this._plus90X);
  62290. }
  62291. //If it is a heightfield, if should be centered.
  62292. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  62293. var mesh = object;
  62294. //calculate the correct body position:
  62295. var rotationQuaternion = mesh.rotationQuaternion;
  62296. mesh.rotationQuaternion = this._tmpUnityRotation;
  62297. mesh.computeWorldMatrix(true);
  62298. //get original center with no rotation
  62299. var c = center.clone();
  62300. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  62301. //rotation is back
  62302. mesh.rotationQuaternion = rotationQuaternion;
  62303. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  62304. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  62305. mesh.setPivotMatrix(p);
  62306. mesh.computeWorldMatrix(true);
  62307. //calculate the translation
  62308. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  62309. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  62310. //add it inverted to the delta
  62311. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  62312. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  62313. mesh.setPivotMatrix(oldPivot);
  62314. mesh.computeWorldMatrix(true);
  62315. }
  62316. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  62317. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  62318. this._tmpPosition.copyFrom(object.position);
  62319. }
  62320. impostor.setDeltaPosition(this._tmpDeltaPosition);
  62321. //Now update the impostor object
  62322. impostor.physicsBody.position.copy(this._tmpPosition);
  62323. impostor.physicsBody.quaternion.copy(quaternion);
  62324. };
  62325. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  62326. impostor.object.position.copyFrom(impostor.physicsBody.position);
  62327. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  62328. };
  62329. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  62330. impostor.physicsBody.position.copy(newPosition);
  62331. impostor.physicsBody.quaternion.copy(newRotation);
  62332. };
  62333. CannonJSPlugin.prototype.isSupported = function () {
  62334. return window.CANNON !== undefined;
  62335. };
  62336. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  62337. impostor.physicsBody.velocity.copy(velocity);
  62338. };
  62339. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  62340. impostor.physicsBody.angularVelocity.copy(velocity);
  62341. };
  62342. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  62343. var v = impostor.physicsBody.velocity;
  62344. if (!v)
  62345. return null;
  62346. return new BABYLON.Vector3(v.x, v.y, v.z);
  62347. };
  62348. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  62349. var v = impostor.physicsBody.angularVelocity;
  62350. if (!v)
  62351. return null;
  62352. return new BABYLON.Vector3(v.x, v.y, v.z);
  62353. };
  62354. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  62355. impostor.physicsBody.mass = mass;
  62356. impostor.physicsBody.updateMassProperties();
  62357. };
  62358. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  62359. return impostor.physicsBody.mass;
  62360. };
  62361. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  62362. return impostor.physicsBody.material.friction;
  62363. };
  62364. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  62365. impostor.physicsBody.material.friction = friction;
  62366. };
  62367. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  62368. return impostor.physicsBody.material.restitution;
  62369. };
  62370. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  62371. impostor.physicsBody.material.restitution = restitution;
  62372. };
  62373. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  62374. impostor.physicsBody.sleep();
  62375. };
  62376. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  62377. impostor.physicsBody.wakeUp();
  62378. };
  62379. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  62380. joint.physicsJoint.distance = maxDistance;
  62381. };
  62382. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  62383. if (!motorIndex) {
  62384. joint.physicsJoint.enableMotor();
  62385. }
  62386. };
  62387. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  62388. if (!motorIndex) {
  62389. joint.physicsJoint.disableMotor();
  62390. }
  62391. };
  62392. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  62393. if (!motorIndex) {
  62394. joint.physicsJoint.enableMotor();
  62395. joint.physicsJoint.setMotorSpeed(speed);
  62396. if (maxForce) {
  62397. this.setLimit(joint, maxForce);
  62398. }
  62399. }
  62400. };
  62401. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  62402. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  62403. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  62404. };
  62405. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  62406. var body = impostor.physicsBody;
  62407. mesh.position.x = body.position.x;
  62408. mesh.position.y = body.position.y;
  62409. mesh.position.z = body.position.z;
  62410. mesh.rotationQuaternion.x = body.quaternion.x;
  62411. mesh.rotationQuaternion.y = body.quaternion.y;
  62412. mesh.rotationQuaternion.z = body.quaternion.z;
  62413. mesh.rotationQuaternion.w = body.quaternion.w;
  62414. };
  62415. CannonJSPlugin.prototype.getRadius = function (impostor) {
  62416. var shape = impostor.physicsBody.shapes[0];
  62417. return shape.boundingSphereRadius;
  62418. };
  62419. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  62420. var shape = impostor.physicsBody.shapes[0];
  62421. result.x = shape.halfExtents.x * 2;
  62422. result.y = shape.halfExtents.y * 2;
  62423. result.z = shape.halfExtents.z * 2;
  62424. };
  62425. CannonJSPlugin.prototype.dispose = function () {
  62426. };
  62427. return CannonJSPlugin;
  62428. }());
  62429. BABYLON.CannonJSPlugin = CannonJSPlugin;
  62430. })(BABYLON || (BABYLON = {}));
  62431. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  62432. var BABYLON;
  62433. (function (BABYLON) {
  62434. var OimoJSPlugin = (function () {
  62435. function OimoJSPlugin(iterations) {
  62436. this.name = "OimoJSPlugin";
  62437. this._tmpImpostorsArray = [];
  62438. this._tmpPositionVector = BABYLON.Vector3.Zero();
  62439. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  62440. this.world.worldscale(1);
  62441. this.world.clear();
  62442. //making sure no stats are calculated
  62443. this.world.isNoStat = true;
  62444. }
  62445. OimoJSPlugin.prototype.setGravity = function (gravity) {
  62446. this.world.gravity.copy(gravity);
  62447. };
  62448. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  62449. this.world.timeStep = timeStep;
  62450. };
  62451. OimoJSPlugin.prototype.getTimeStep = function () {
  62452. return this.world.timeStep;
  62453. };
  62454. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  62455. var _this = this;
  62456. impostors.forEach(function (impostor) {
  62457. impostor.beforeStep();
  62458. });
  62459. this.world.step();
  62460. impostors.forEach(function (impostor) {
  62461. impostor.afterStep();
  62462. //update the ordered impostors array
  62463. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  62464. });
  62465. //check for collisions
  62466. var contact = this.world.contacts;
  62467. while (contact !== null) {
  62468. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  62469. contact = contact.next;
  62470. continue;
  62471. }
  62472. //is this body colliding with any other? get the impostor
  62473. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  62474. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  62475. if (!mainImpostor || !collidingImpostor) {
  62476. contact = contact.next;
  62477. continue;
  62478. }
  62479. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  62480. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  62481. contact = contact.next;
  62482. }
  62483. };
  62484. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  62485. var mass = impostor.physicsBody.massInfo.mass;
  62486. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  62487. };
  62488. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  62489. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  62490. this.applyImpulse(impostor, force, contactPoint);
  62491. };
  62492. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  62493. var _this = this;
  62494. //parent-child relationship. Does this impostor has a parent impostor?
  62495. if (impostor.parent) {
  62496. if (impostor.physicsBody) {
  62497. this.removePhysicsBody(impostor);
  62498. //TODO is that needed?
  62499. impostor.forceUpdate();
  62500. }
  62501. return;
  62502. }
  62503. if (impostor.isBodyInitRequired()) {
  62504. var bodyConfig = {
  62505. name: impostor.uniqueId,
  62506. //Oimo must have mass, also for static objects.
  62507. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  62508. size: [],
  62509. type: [],
  62510. pos: [],
  62511. rot: [],
  62512. move: impostor.getParam("mass") !== 0,
  62513. //Supporting older versions of Oimo
  62514. world: this.world
  62515. };
  62516. var impostors = [impostor];
  62517. var addToArray = function (parent) {
  62518. if (!parent.getChildMeshes)
  62519. return;
  62520. parent.getChildMeshes().forEach(function (m) {
  62521. if (m.physicsImpostor) {
  62522. impostors.push(m.physicsImpostor);
  62523. m.physicsImpostor._init();
  62524. }
  62525. });
  62526. };
  62527. addToArray(impostor.object);
  62528. var checkWithEpsilon_1 = function (value) {
  62529. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  62530. };
  62531. impostors.forEach(function (i) {
  62532. //get the correct bounding box
  62533. var oldQuaternion = i.object.rotationQuaternion;
  62534. var rot = new OIMO.Euler().setFromQuaternion({
  62535. x: impostor.object.rotationQuaternion.x,
  62536. y: impostor.object.rotationQuaternion.y,
  62537. z: impostor.object.rotationQuaternion.z,
  62538. s: impostor.object.rotationQuaternion.w
  62539. });
  62540. var extendSize = i.getObjectExtendSize();
  62541. if (i === impostor) {
  62542. var center = impostor.getObjectCenter();
  62543. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  62544. //Can also use Array.prototype.push.apply
  62545. bodyConfig.pos.push(center.x);
  62546. bodyConfig.pos.push(center.y);
  62547. bodyConfig.pos.push(center.z);
  62548. //tmp solution
  62549. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  62550. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  62551. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  62552. }
  62553. else {
  62554. bodyConfig.pos.push(i.object.position.x);
  62555. bodyConfig.pos.push(i.object.position.y);
  62556. bodyConfig.pos.push(i.object.position.z);
  62557. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  62558. bodyConfig.rot.push(0);
  62559. bodyConfig.rot.push(0);
  62560. bodyConfig.rot.push(0);
  62561. }
  62562. // register mesh
  62563. switch (i.type) {
  62564. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62565. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  62566. case BABYLON.PhysicsImpostor.SphereImpostor:
  62567. var radiusX = extendSize.x;
  62568. var radiusY = extendSize.y;
  62569. var radiusZ = extendSize.z;
  62570. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  62571. bodyConfig.type.push('sphere');
  62572. //due to the way oimo works with compounds, add 3 times
  62573. bodyConfig.size.push(size);
  62574. bodyConfig.size.push(size);
  62575. bodyConfig.size.push(size);
  62576. break;
  62577. case BABYLON.PhysicsImpostor.CylinderImpostor:
  62578. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  62579. var sizeY = checkWithEpsilon_1(extendSize.y);
  62580. bodyConfig.type.push('cylinder');
  62581. bodyConfig.size.push(sizeX);
  62582. bodyConfig.size.push(sizeY);
  62583. //due to the way oimo works with compounds, add one more value.
  62584. bodyConfig.size.push(sizeY);
  62585. break;
  62586. case BABYLON.PhysicsImpostor.PlaneImpostor:
  62587. case BABYLON.PhysicsImpostor.BoxImpostor:
  62588. default:
  62589. var sizeX = checkWithEpsilon_1(extendSize.x);
  62590. var sizeY = checkWithEpsilon_1(extendSize.y);
  62591. var sizeZ = checkWithEpsilon_1(extendSize.z);
  62592. bodyConfig.type.push('box');
  62593. bodyConfig.size.push(sizeX);
  62594. bodyConfig.size.push(sizeY);
  62595. bodyConfig.size.push(sizeZ);
  62596. break;
  62597. }
  62598. //actually not needed, but hey...
  62599. i.object.rotationQuaternion = oldQuaternion;
  62600. });
  62601. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  62602. }
  62603. else {
  62604. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  62605. }
  62606. impostor.setDeltaPosition(this._tmpPositionVector);
  62607. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  62608. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  62609. };
  62610. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  62611. //impostor.physicsBody.dispose();
  62612. //Same as : (older oimo versions)
  62613. this.world.removeRigidBody(impostor.physicsBody);
  62614. };
  62615. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  62616. var mainBody = impostorJoint.mainImpostor.physicsBody;
  62617. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  62618. if (!mainBody || !connectedBody) {
  62619. return;
  62620. }
  62621. var jointData = impostorJoint.joint.jointData;
  62622. var options = jointData.nativeParams || {};
  62623. var type;
  62624. var nativeJointData = {
  62625. body1: mainBody,
  62626. body2: connectedBody,
  62627. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  62628. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  62629. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  62630. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  62631. min: options.min,
  62632. max: options.max,
  62633. collision: options.collision || jointData.collision,
  62634. spring: options.spring,
  62635. //supporting older version of Oimo
  62636. world: this.world
  62637. };
  62638. switch (impostorJoint.joint.type) {
  62639. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  62640. type = "jointBall";
  62641. break;
  62642. case BABYLON.PhysicsJoint.SpringJoint:
  62643. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  62644. var springData = jointData;
  62645. nativeJointData.min = springData.length || nativeJointData.min;
  62646. //Max should also be set, just make sure it is at least min
  62647. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  62648. case BABYLON.PhysicsJoint.DistanceJoint:
  62649. type = "jointDistance";
  62650. nativeJointData.max = jointData.maxDistance;
  62651. break;
  62652. case BABYLON.PhysicsJoint.PrismaticJoint:
  62653. type = "jointPrisme";
  62654. break;
  62655. case BABYLON.PhysicsJoint.SliderJoint:
  62656. type = "jointSlide";
  62657. break;
  62658. case BABYLON.PhysicsJoint.WheelJoint:
  62659. type = "jointWheel";
  62660. break;
  62661. case BABYLON.PhysicsJoint.HingeJoint:
  62662. default:
  62663. type = "jointHinge";
  62664. break;
  62665. }
  62666. nativeJointData.type = type;
  62667. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  62668. };
  62669. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  62670. //Bug in Oimo prevents us from disposing a joint in the playground
  62671. //joint.joint.physicsJoint.dispose();
  62672. //So we will bruteforce it!
  62673. try {
  62674. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  62675. }
  62676. catch (e) {
  62677. BABYLON.Tools.Warn(e);
  62678. }
  62679. };
  62680. OimoJSPlugin.prototype.isSupported = function () {
  62681. return OIMO !== undefined;
  62682. };
  62683. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  62684. if (!impostor.physicsBody.sleeping) {
  62685. //TODO check that
  62686. if (impostor.physicsBody.shapes.next) {
  62687. var parentShape = this._getLastShape(impostor.physicsBody);
  62688. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  62689. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  62690. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  62691. }
  62692. else {
  62693. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  62694. }
  62695. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  62696. impostor.object.rotationQuaternion.normalize();
  62697. }
  62698. };
  62699. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  62700. var body = impostor.physicsBody;
  62701. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  62702. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  62703. body.syncShapes();
  62704. body.awake();
  62705. };
  62706. OimoJSPlugin.prototype._getLastShape = function (body) {
  62707. var lastShape = body.shapes;
  62708. while (lastShape.next) {
  62709. lastShape = lastShape.next;
  62710. }
  62711. return lastShape;
  62712. };
  62713. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  62714. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  62715. };
  62716. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  62717. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  62718. };
  62719. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  62720. var v = impostor.physicsBody.linearVelocity;
  62721. if (!v)
  62722. return null;
  62723. return new BABYLON.Vector3(v.x, v.y, v.z);
  62724. };
  62725. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  62726. var v = impostor.physicsBody.angularVelocity;
  62727. if (!v)
  62728. return null;
  62729. return new BABYLON.Vector3(v.x, v.y, v.z);
  62730. };
  62731. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  62732. var staticBody = mass === 0;
  62733. //this will actually set the body's density and not its mass.
  62734. //But this is how oimo treats the mass variable.
  62735. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  62736. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  62737. };
  62738. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  62739. return impostor.physicsBody.shapes.density;
  62740. };
  62741. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  62742. return impostor.physicsBody.shapes.friction;
  62743. };
  62744. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  62745. impostor.physicsBody.shapes.friction = friction;
  62746. };
  62747. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  62748. return impostor.physicsBody.shapes.restitution;
  62749. };
  62750. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  62751. impostor.physicsBody.shapes.restitution = restitution;
  62752. };
  62753. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  62754. impostor.physicsBody.sleep();
  62755. };
  62756. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  62757. impostor.physicsBody.awake();
  62758. };
  62759. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  62760. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  62761. if (minDistance !== void 0) {
  62762. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  62763. }
  62764. };
  62765. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  62766. //TODO separate rotational and transational motors.
  62767. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  62768. if (motor) {
  62769. motor.setMotor(speed, maxForce);
  62770. }
  62771. };
  62772. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  62773. //TODO separate rotational and transational motors.
  62774. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  62775. if (motor) {
  62776. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  62777. }
  62778. };
  62779. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  62780. var body = impostor.physicsBody;
  62781. mesh.position.x = body.position.x;
  62782. mesh.position.y = body.position.y;
  62783. mesh.position.z = body.position.z;
  62784. mesh.rotationQuaternion.x = body.orientation.x;
  62785. mesh.rotationQuaternion.y = body.orientation.y;
  62786. mesh.rotationQuaternion.z = body.orientation.z;
  62787. mesh.rotationQuaternion.w = body.orientation.s;
  62788. };
  62789. OimoJSPlugin.prototype.getRadius = function (impostor) {
  62790. return impostor.physicsBody.shapes.radius;
  62791. };
  62792. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  62793. var shape = impostor.physicsBody.shapes;
  62794. result.x = shape.halfWidth * 2;
  62795. result.y = shape.halfHeight * 2;
  62796. result.z = shape.halfDepth * 2;
  62797. };
  62798. OimoJSPlugin.prototype.dispose = function () {
  62799. this.world.clear();
  62800. };
  62801. return OimoJSPlugin;
  62802. }());
  62803. BABYLON.OimoJSPlugin = OimoJSPlugin;
  62804. })(BABYLON || (BABYLON = {}));
  62805. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  62806. var BABYLON;
  62807. (function (BABYLON) {
  62808. var Internals;
  62809. (function (Internals) {
  62810. /*
  62811. * Based on jsTGALoader - Javascript loader for TGA file
  62812. * By Vincent Thibault
  62813. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  62814. */
  62815. var TGATools = (function () {
  62816. function TGATools() {
  62817. }
  62818. TGATools.GetTGAHeader = function (data) {
  62819. var offset = 0;
  62820. var header = {
  62821. id_length: data[offset++],
  62822. colormap_type: data[offset++],
  62823. image_type: data[offset++],
  62824. colormap_index: data[offset++] | data[offset++] << 8,
  62825. colormap_length: data[offset++] | data[offset++] << 8,
  62826. colormap_size: data[offset++],
  62827. origin: [
  62828. data[offset++] | data[offset++] << 8,
  62829. data[offset++] | data[offset++] << 8
  62830. ],
  62831. width: data[offset++] | data[offset++] << 8,
  62832. height: data[offset++] | data[offset++] << 8,
  62833. pixel_size: data[offset++],
  62834. flags: data[offset++]
  62835. };
  62836. return header;
  62837. };
  62838. TGATools.UploadContent = function (gl, data) {
  62839. // Not enough data to contain header ?
  62840. if (data.length < 19) {
  62841. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  62842. return;
  62843. }
  62844. // Read Header
  62845. var offset = 18;
  62846. var header = TGATools.GetTGAHeader(data);
  62847. // Assume it's a valid Targa file.
  62848. if (header.id_length + offset > data.length) {
  62849. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  62850. return;
  62851. }
  62852. // Skip not needed data
  62853. offset += header.id_length;
  62854. var use_rle = false;
  62855. var use_pal = false;
  62856. var use_rgb = false;
  62857. var use_grey = false;
  62858. // Get some informations.
  62859. switch (header.image_type) {
  62860. case TGATools._TYPE_RLE_INDEXED:
  62861. use_rle = true;
  62862. case TGATools._TYPE_INDEXED:
  62863. use_pal = true;
  62864. break;
  62865. case TGATools._TYPE_RLE_RGB:
  62866. use_rle = true;
  62867. case TGATools._TYPE_RGB:
  62868. use_rgb = true;
  62869. break;
  62870. case TGATools._TYPE_RLE_GREY:
  62871. use_rle = true;
  62872. case TGATools._TYPE_GREY:
  62873. use_grey = true;
  62874. break;
  62875. }
  62876. var pixel_data;
  62877. var numAlphaBits = header.flags & 0xf;
  62878. var pixel_size = header.pixel_size >> 3;
  62879. var pixel_total = header.width * header.height * pixel_size;
  62880. // Read palettes
  62881. var palettes;
  62882. if (use_pal) {
  62883. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  62884. }
  62885. // Read LRE
  62886. if (use_rle) {
  62887. pixel_data = new Uint8Array(pixel_total);
  62888. var c, count, i;
  62889. var localOffset = 0;
  62890. var pixels = new Uint8Array(pixel_size);
  62891. while (offset < pixel_total && localOffset < pixel_total) {
  62892. c = data[offset++];
  62893. count = (c & 0x7f) + 1;
  62894. // RLE pixels
  62895. if (c & 0x80) {
  62896. // Bind pixel tmp array
  62897. for (i = 0; i < pixel_size; ++i) {
  62898. pixels[i] = data[offset++];
  62899. }
  62900. // Copy pixel array
  62901. for (i = 0; i < count; ++i) {
  62902. pixel_data.set(pixels, localOffset + i * pixel_size);
  62903. }
  62904. localOffset += pixel_size * count;
  62905. }
  62906. else {
  62907. count *= pixel_size;
  62908. for (i = 0; i < count; ++i) {
  62909. pixel_data[localOffset + i] = data[offset++];
  62910. }
  62911. localOffset += count;
  62912. }
  62913. }
  62914. }
  62915. else {
  62916. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  62917. }
  62918. // Load to texture
  62919. var x_start, y_start, x_step, y_step, y_end, x_end;
  62920. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  62921. default:
  62922. case TGATools._ORIGIN_UL:
  62923. x_start = 0;
  62924. x_step = 1;
  62925. x_end = header.width;
  62926. y_start = 0;
  62927. y_step = 1;
  62928. y_end = header.height;
  62929. break;
  62930. case TGATools._ORIGIN_BL:
  62931. x_start = 0;
  62932. x_step = 1;
  62933. x_end = header.width;
  62934. y_start = header.height - 1;
  62935. y_step = -1;
  62936. y_end = -1;
  62937. break;
  62938. case TGATools._ORIGIN_UR:
  62939. x_start = header.width - 1;
  62940. x_step = -1;
  62941. x_end = -1;
  62942. y_start = 0;
  62943. y_step = 1;
  62944. y_end = header.height;
  62945. break;
  62946. case TGATools._ORIGIN_BR:
  62947. x_start = header.width - 1;
  62948. x_step = -1;
  62949. x_end = -1;
  62950. y_start = header.height - 1;
  62951. y_step = -1;
  62952. y_end = -1;
  62953. break;
  62954. }
  62955. // Load the specify method
  62956. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  62957. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  62958. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  62959. };
  62960. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62961. var image = pixel_data, colormap = palettes;
  62962. var width = header.width, height = header.height;
  62963. var color, i = 0, x, y;
  62964. var imageData = new Uint8Array(width * height * 4);
  62965. for (y = y_start; y !== y_end; y += y_step) {
  62966. for (x = x_start; x !== x_end; x += x_step, i++) {
  62967. color = image[i];
  62968. imageData[(x + width * y) * 4 + 3] = 255;
  62969. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  62970. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  62971. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  62972. }
  62973. }
  62974. return imageData;
  62975. };
  62976. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62977. var image = pixel_data;
  62978. var width = header.width, height = header.height;
  62979. var color, i = 0, x, y;
  62980. var imageData = new Uint8Array(width * height * 4);
  62981. for (y = y_start; y !== y_end; y += y_step) {
  62982. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  62983. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  62984. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  62985. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  62986. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  62987. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  62988. }
  62989. }
  62990. return imageData;
  62991. };
  62992. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62993. var image = pixel_data;
  62994. var width = header.width, height = header.height;
  62995. var i = 0, x, y;
  62996. var imageData = new Uint8Array(width * height * 4);
  62997. for (y = y_start; y !== y_end; y += y_step) {
  62998. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  62999. imageData[(x + width * y) * 4 + 3] = 255;
  63000. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63001. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  63002. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  63003. }
  63004. }
  63005. return imageData;
  63006. };
  63007. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63008. var image = pixel_data;
  63009. var width = header.width, height = header.height;
  63010. var i = 0, x, y;
  63011. var imageData = new Uint8Array(width * height * 4);
  63012. for (y = y_start; y !== y_end; y += y_step) {
  63013. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  63014. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63015. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  63016. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  63017. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  63018. }
  63019. }
  63020. return imageData;
  63021. };
  63022. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63023. var image = pixel_data;
  63024. var width = header.width, height = header.height;
  63025. var color, i = 0, x, y;
  63026. var imageData = new Uint8Array(width * height * 4);
  63027. for (y = y_start; y !== y_end; y += y_step) {
  63028. for (x = x_start; x !== x_end; x += x_step, i++) {
  63029. color = image[i];
  63030. imageData[(x + width * y) * 4 + 0] = color;
  63031. imageData[(x + width * y) * 4 + 1] = color;
  63032. imageData[(x + width * y) * 4 + 2] = color;
  63033. imageData[(x + width * y) * 4 + 3] = 255;
  63034. }
  63035. }
  63036. return imageData;
  63037. };
  63038. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63039. var image = pixel_data;
  63040. var width = header.width, height = header.height;
  63041. var i = 0, x, y;
  63042. var imageData = new Uint8Array(width * height * 4);
  63043. for (y = y_start; y !== y_end; y += y_step) {
  63044. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  63045. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  63046. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  63047. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63048. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  63049. }
  63050. }
  63051. return imageData;
  63052. };
  63053. TGATools._TYPE_NO_DATA = 0;
  63054. TGATools._TYPE_INDEXED = 1;
  63055. TGATools._TYPE_RGB = 2;
  63056. TGATools._TYPE_GREY = 3;
  63057. TGATools._TYPE_RLE_INDEXED = 9;
  63058. TGATools._TYPE_RLE_RGB = 10;
  63059. TGATools._TYPE_RLE_GREY = 11;
  63060. TGATools._ORIGIN_MASK = 0x30;
  63061. TGATools._ORIGIN_SHIFT = 0x04;
  63062. TGATools._ORIGIN_BL = 0x00;
  63063. TGATools._ORIGIN_BR = 0x01;
  63064. TGATools._ORIGIN_UL = 0x02;
  63065. TGATools._ORIGIN_UR = 0x03;
  63066. return TGATools;
  63067. }());
  63068. Internals.TGATools = TGATools;
  63069. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63070. })(BABYLON || (BABYLON = {}));
  63071. //# sourceMappingURL=babylon.tga.js.map
  63072. var BABYLON;
  63073. (function (BABYLON) {
  63074. var Internals;
  63075. (function (Internals) {
  63076. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  63077. // All values and structures referenced from:
  63078. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  63079. var DDS_MAGIC = 0x20534444;
  63080. 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;
  63081. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  63082. 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;
  63083. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  63084. function FourCCToInt32(value) {
  63085. return value.charCodeAt(0) +
  63086. (value.charCodeAt(1) << 8) +
  63087. (value.charCodeAt(2) << 16) +
  63088. (value.charCodeAt(3) << 24);
  63089. }
  63090. function Int32ToFourCC(value) {
  63091. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  63092. }
  63093. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  63094. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  63095. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  63096. var FOURCC_DX10 = FourCCToInt32("DX10");
  63097. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  63098. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  63099. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  63100. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  63101. var headerLengthInt = 31; // The header length in 32 bit ints
  63102. // Offsets into the header array
  63103. var off_magic = 0;
  63104. var off_size = 1;
  63105. var off_flags = 2;
  63106. var off_height = 3;
  63107. var off_width = 4;
  63108. var off_mipmapCount = 7;
  63109. var off_pfFlags = 20;
  63110. var off_pfFourCC = 21;
  63111. var off_RGBbpp = 22;
  63112. var off_RMask = 23;
  63113. var off_GMask = 24;
  63114. var off_BMask = 25;
  63115. var off_AMask = 26;
  63116. var off_caps1 = 27;
  63117. var off_caps2 = 28;
  63118. var off_caps3 = 29;
  63119. var off_caps4 = 30;
  63120. var off_dxgiFormat = 32;
  63121. ;
  63122. var DDSTools = (function () {
  63123. function DDSTools() {
  63124. }
  63125. DDSTools.GetDDSInfo = function (arrayBuffer) {
  63126. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  63127. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  63128. var mipmapCount = 1;
  63129. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  63130. mipmapCount = Math.max(1, header[off_mipmapCount]);
  63131. }
  63132. var fourCC = header[off_pfFourCC];
  63133. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  63134. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63135. switch (fourCC) {
  63136. case FOURCC_D3DFMT_R16G16B16A16F:
  63137. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63138. break;
  63139. case FOURCC_D3DFMT_R32G32B32A32F:
  63140. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63141. break;
  63142. case FOURCC_DX10:
  63143. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  63144. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63145. break;
  63146. }
  63147. }
  63148. return {
  63149. width: header[off_width],
  63150. height: header[off_height],
  63151. mipmapCount: mipmapCount,
  63152. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  63153. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  63154. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  63155. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  63156. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  63157. dxgiFormat: dxgiFormat,
  63158. textureType: textureType
  63159. };
  63160. };
  63161. DDSTools._ToHalfFloat = function (value) {
  63162. if (!DDSTools._FloatView) {
  63163. DDSTools._FloatView = new Float32Array(1);
  63164. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  63165. }
  63166. DDSTools._FloatView[0] = value;
  63167. var x = DDSTools._Int32View[0];
  63168. var bits = (x >> 16) & 0x8000; /* Get the sign */
  63169. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  63170. var e = (x >> 23) & 0xff; /* Using int is faster here */
  63171. /* If zero, or denormal, or exponent underflows too much for a denormal
  63172. * half, return signed zero. */
  63173. if (e < 103) {
  63174. return bits;
  63175. }
  63176. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  63177. if (e > 142) {
  63178. bits |= 0x7c00;
  63179. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  63180. * not Inf, so make sure we set one mantissa bit too. */
  63181. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  63182. return bits;
  63183. }
  63184. /* If exponent underflows but not too much, return a denormal */
  63185. if (e < 113) {
  63186. m |= 0x0800;
  63187. /* Extra rounding may overflow and set mantissa to 0 and exponent
  63188. * to 1, which is OK. */
  63189. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  63190. return bits;
  63191. }
  63192. bits |= ((e - 112) << 10) | (m >> 1);
  63193. bits += m & 1;
  63194. return bits;
  63195. };
  63196. DDSTools._FromHalfFloat = function (value) {
  63197. var s = (value & 0x8000) >> 15;
  63198. var e = (value & 0x7C00) >> 10;
  63199. var f = value & 0x03FF;
  63200. if (e === 0) {
  63201. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  63202. }
  63203. else if (e == 0x1F) {
  63204. return f ? NaN : ((s ? -1 : 1) * Infinity);
  63205. }
  63206. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  63207. };
  63208. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63209. var destArray = new Float32Array(dataLength);
  63210. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63211. var index = 0;
  63212. for (var y = 0; y < height; y++) {
  63213. for (var x = 0; x < width; x++) {
  63214. var srcPos = (x + y * width) * 4;
  63215. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  63216. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  63217. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  63218. if (DDSTools.StoreLODInAlphaChannel) {
  63219. destArray[index + 3] = lod;
  63220. }
  63221. else {
  63222. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  63223. }
  63224. index += 4;
  63225. }
  63226. }
  63227. return destArray;
  63228. };
  63229. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63230. if (DDSTools.StoreLODInAlphaChannel) {
  63231. var destArray = new Uint16Array(dataLength);
  63232. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63233. var index = 0;
  63234. for (var y = 0; y < height; y++) {
  63235. for (var x = 0; x < width; x++) {
  63236. var srcPos = (x + y * width) * 4;
  63237. destArray[index] = srcData[srcPos];
  63238. destArray[index + 1] = srcData[srcPos + 1];
  63239. destArray[index + 2] = srcData[srcPos + 2];
  63240. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  63241. index += 4;
  63242. }
  63243. }
  63244. return destArray;
  63245. }
  63246. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  63247. };
  63248. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63249. if (DDSTools.StoreLODInAlphaChannel) {
  63250. var destArray = new Float32Array(dataLength);
  63251. var srcData = new Float32Array(arrayBuffer, dataOffset);
  63252. var index = 0;
  63253. for (var y = 0; y < height; y++) {
  63254. for (var x = 0; x < width; x++) {
  63255. var srcPos = (x + y * width) * 4;
  63256. destArray[index] = srcData[srcPos];
  63257. destArray[index + 1] = srcData[srcPos + 1];
  63258. destArray[index + 2] = srcData[srcPos + 2];
  63259. destArray[index + 3] = lod;
  63260. index += 4;
  63261. }
  63262. }
  63263. return destArray;
  63264. }
  63265. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  63266. };
  63267. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63268. var destArray = new Uint8Array(dataLength);
  63269. var srcData = new Float32Array(arrayBuffer, dataOffset);
  63270. var index = 0;
  63271. for (var y = 0; y < height; y++) {
  63272. for (var x = 0; x < width; x++) {
  63273. var srcPos = (x + y * width) * 4;
  63274. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  63275. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  63276. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  63277. if (DDSTools.StoreLODInAlphaChannel) {
  63278. destArray[index + 3] = lod;
  63279. }
  63280. else {
  63281. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  63282. }
  63283. index += 4;
  63284. }
  63285. }
  63286. return destArray;
  63287. };
  63288. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63289. var destArray = new Uint8Array(dataLength);
  63290. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63291. var index = 0;
  63292. for (var y = 0; y < height; y++) {
  63293. for (var x = 0; x < width; x++) {
  63294. var srcPos = (x + y * width) * 4;
  63295. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  63296. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  63297. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  63298. if (DDSTools.StoreLODInAlphaChannel) {
  63299. destArray[index + 3] = lod;
  63300. }
  63301. else {
  63302. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  63303. }
  63304. index += 4;
  63305. }
  63306. }
  63307. return destArray;
  63308. };
  63309. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63310. var byteArray = new Uint8Array(dataLength);
  63311. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63312. var index = 0;
  63313. for (var y = 0; y < height; y++) {
  63314. for (var x = 0; x < width; x++) {
  63315. var srcPos = (x + y * width) * 4;
  63316. byteArray[index] = srcData[srcPos + 2];
  63317. byteArray[index + 1] = srcData[srcPos + 1];
  63318. byteArray[index + 2] = srcData[srcPos];
  63319. byteArray[index + 3] = srcData[srcPos + 3];
  63320. index += 4;
  63321. }
  63322. }
  63323. return byteArray;
  63324. };
  63325. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63326. var byteArray = new Uint8Array(dataLength);
  63327. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63328. var index = 0;
  63329. for (var y = 0; y < height; y++) {
  63330. for (var x = 0; x < width; x++) {
  63331. var srcPos = (x + y * width) * 3;
  63332. byteArray[index] = srcData[srcPos + 2];
  63333. byteArray[index + 1] = srcData[srcPos + 1];
  63334. byteArray[index + 2] = srcData[srcPos];
  63335. index += 3;
  63336. }
  63337. }
  63338. return byteArray;
  63339. };
  63340. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63341. var byteArray = new Uint8Array(dataLength);
  63342. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63343. var index = 0;
  63344. for (var y = 0; y < height; y++) {
  63345. for (var x = 0; x < width; x++) {
  63346. var srcPos = (x + y * width);
  63347. byteArray[index] = srcData[srcPos];
  63348. index++;
  63349. }
  63350. }
  63351. return byteArray;
  63352. };
  63353. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  63354. if (lodIndex === void 0) { lodIndex = -1; }
  63355. var ext = engine.getCaps().s3tc;
  63356. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  63357. if (header[off_magic] != DDS_MAGIC) {
  63358. BABYLON.Tools.Error("Invalid magic number in DDS header");
  63359. return;
  63360. }
  63361. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  63362. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  63363. return;
  63364. }
  63365. if (info.isCompressed && !ext) {
  63366. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  63367. return;
  63368. }
  63369. var bpp = header[off_RGBbpp];
  63370. dataOffset = header[off_size] + 4;
  63371. var computeFormats = false;
  63372. if (info.isFourCC) {
  63373. fourCC = header[off_pfFourCC];
  63374. switch (fourCC) {
  63375. case FOURCC_DXT1:
  63376. blockBytes = 8;
  63377. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  63378. break;
  63379. case FOURCC_DXT3:
  63380. blockBytes = 16;
  63381. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  63382. break;
  63383. case FOURCC_DXT5:
  63384. blockBytes = 16;
  63385. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  63386. break;
  63387. case FOURCC_D3DFMT_R16G16B16A16F:
  63388. computeFormats = true;
  63389. break;
  63390. case FOURCC_D3DFMT_R32G32B32A32F:
  63391. computeFormats = true;
  63392. break;
  63393. case FOURCC_DX10:
  63394. // There is an additionnal header so dataOffset need to be changed
  63395. dataOffset += 5 * 4; // 5 uints
  63396. var supported = false;
  63397. switch (info.dxgiFormat) {
  63398. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  63399. computeFormats = true;
  63400. supported = true;
  63401. break;
  63402. case DXGI_FORMAT_B8G8R8X8_UNORM:
  63403. info.isRGB = true;
  63404. info.isFourCC = false;
  63405. bpp = 32;
  63406. supported = true;
  63407. break;
  63408. }
  63409. if (supported) {
  63410. break;
  63411. }
  63412. default:
  63413. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  63414. return;
  63415. }
  63416. }
  63417. if (computeFormats) {
  63418. format = engine._getWebGLTextureType(info.textureType);
  63419. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63420. }
  63421. mipmapCount = 1;
  63422. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  63423. mipmapCount = Math.max(1, header[off_mipmapCount]);
  63424. }
  63425. for (var face = 0; face < faces; face++) {
  63426. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  63427. width = header[off_width];
  63428. height = header[off_height];
  63429. for (mip = 0; mip < mipmapCount; ++mip) {
  63430. if (lodIndex === -1 || lodIndex === mip) {
  63431. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  63432. var i = (lodIndex === -1) ? mip : 0;
  63433. if (!info.isCompressed && info.isFourCC) {
  63434. dataLength = width * height * 4;
  63435. var floatArray;
  63436. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  63437. if (bpp === 128) {
  63438. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63439. }
  63440. else if (bpp === 64) {
  63441. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63442. }
  63443. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63444. format = engine._getWebGLTextureType(info.textureType);
  63445. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63446. }
  63447. else {
  63448. if (bpp === 128) {
  63449. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63450. }
  63451. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  63452. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63453. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63454. format = engine._getWebGLTextureType(info.textureType);
  63455. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63456. }
  63457. else {
  63458. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63459. }
  63460. }
  63461. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  63462. }
  63463. else if (info.isRGB) {
  63464. if (bpp === 24) {
  63465. dataLength = width * height * 3;
  63466. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63467. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  63468. }
  63469. else {
  63470. dataLength = width * height * 4;
  63471. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63472. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  63473. }
  63474. }
  63475. else if (info.isLuminance) {
  63476. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  63477. var unpaddedRowSize = width;
  63478. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  63479. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  63480. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63481. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  63482. }
  63483. else {
  63484. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  63485. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  63486. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  63487. }
  63488. }
  63489. dataOffset += width * height * (bpp / 8);
  63490. width *= 0.5;
  63491. height *= 0.5;
  63492. width = Math.max(1.0, width);
  63493. height = Math.max(1.0, height);
  63494. }
  63495. }
  63496. };
  63497. DDSTools.StoreLODInAlphaChannel = false;
  63498. return DDSTools;
  63499. }());
  63500. Internals.DDSTools = DDSTools;
  63501. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63502. })(BABYLON || (BABYLON = {}));
  63503. //# sourceMappingURL=babylon.dds.js.map
  63504. var BABYLON;
  63505. (function (BABYLON) {
  63506. var Internals;
  63507. (function (Internals) {
  63508. /**
  63509. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  63510. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  63511. */
  63512. var KhronosTextureContainer = (function () {
  63513. /**
  63514. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  63515. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  63516. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  63517. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  63518. */
  63519. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  63520. this.arrayBuffer = arrayBuffer;
  63521. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  63522. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  63523. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  63524. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  63525. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  63526. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  63527. BABYLON.Tools.Error("texture missing KTX identifier");
  63528. return;
  63529. }
  63530. // load the reset of the header in native 32 bit int
  63531. var header = new Int32Array(this.arrayBuffer, 12, 13);
  63532. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  63533. var oppositeEndianess = header[0] === 0x01020304;
  63534. // read all the header elements in order they exist in the file, without modification (sans endainness)
  63535. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  63536. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  63537. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  63538. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  63539. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  63540. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  63541. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  63542. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  63543. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  63544. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  63545. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  63546. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  63547. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  63548. if (this.glType !== 0) {
  63549. BABYLON.Tools.Error("only compressed formats currently supported");
  63550. return;
  63551. }
  63552. else {
  63553. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  63554. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  63555. }
  63556. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  63557. BABYLON.Tools.Error("only 2D textures currently supported");
  63558. return;
  63559. }
  63560. if (this.numberOfArrayElements !== 0) {
  63561. BABYLON.Tools.Error("texture arrays not currently supported");
  63562. return;
  63563. }
  63564. if (this.numberOfFaces !== facesExpected) {
  63565. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  63566. return;
  63567. }
  63568. // we now have a completely validated file, so could use existence of loadType as success
  63569. // would need to make this more elaborate & adjust checks above to support more than one load type
  63570. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  63571. }
  63572. // not as fast hardware based, but will probably never need to use
  63573. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  63574. return ((val & 0xFF) << 24)
  63575. | ((val & 0xFF00) << 8)
  63576. | ((val >> 8) & 0xFF00)
  63577. | ((val >> 24) & 0xFF);
  63578. };
  63579. /**
  63580. * It is assumed that the texture has already been created & is currently bound
  63581. */
  63582. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  63583. switch (this.loadType) {
  63584. case KhronosTextureContainer.COMPRESSED_2D:
  63585. this._upload2DCompressedLevels(gl, loadMipmaps);
  63586. break;
  63587. case KhronosTextureContainer.TEX_2D:
  63588. case KhronosTextureContainer.COMPRESSED_3D:
  63589. case KhronosTextureContainer.TEX_3D:
  63590. }
  63591. };
  63592. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  63593. // initialize width & height for level 1
  63594. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  63595. var width = this.pixelWidth;
  63596. var height = this.pixelHeight;
  63597. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  63598. for (var level = 0; level < mipmapCount; level++) {
  63599. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  63600. for (var face = 0; face < this.numberOfFaces; face++) {
  63601. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  63602. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  63603. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  63604. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  63605. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  63606. }
  63607. width = Math.max(1.0, width * 0.5);
  63608. height = Math.max(1.0, height * 0.5);
  63609. }
  63610. };
  63611. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  63612. // load types
  63613. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  63614. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  63615. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  63616. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  63617. return KhronosTextureContainer;
  63618. }());
  63619. Internals.KhronosTextureContainer = KhronosTextureContainer;
  63620. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63621. })(BABYLON || (BABYLON = {}));
  63622. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  63623. var BABYLON;
  63624. (function (BABYLON) {
  63625. var DynamicFloatArrayElementInfo = (function () {
  63626. function DynamicFloatArrayElementInfo() {
  63627. }
  63628. return DynamicFloatArrayElementInfo;
  63629. }());
  63630. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  63631. /**
  63632. * 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.
  63633. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  63634. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  63635. * 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.
  63636. * 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.
  63637. * 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".
  63638. */
  63639. var DynamicFloatArray = (function () {
  63640. /**
  63641. * Construct an instance of the dynamic float array
  63642. * @param stride size of one element in float (i.e. not bytes!)
  63643. * @param initialElementCount the number of available entries at construction
  63644. */
  63645. function DynamicFloatArray(stride, initialElementCount) {
  63646. this.compareValueOffset = null;
  63647. this.sortingAscending = true;
  63648. this._stride = stride;
  63649. this.buffer = new Float32Array(stride * initialElementCount);
  63650. this._lastUsed = 0;
  63651. this._firstFree = 0;
  63652. this._allEntries = new Array(initialElementCount);
  63653. this._freeEntries = new Array(initialElementCount);
  63654. for (var i = 0; i < initialElementCount; i++) {
  63655. var element = new DynamicFloatArrayElementInfo();
  63656. element.offset = i * stride;
  63657. this._allEntries[i] = element;
  63658. this._freeEntries[initialElementCount - i - 1] = element;
  63659. }
  63660. }
  63661. /**
  63662. * Allocate an element in the array.
  63663. * @return the element info instance that contains the offset into the main buffer of the element's location.
  63664. * Beware, this offset may change when you call pack()
  63665. */
  63666. DynamicFloatArray.prototype.allocElement = function () {
  63667. if (this._freeEntries.length === 0) {
  63668. this._growBuffer();
  63669. }
  63670. var el = this._freeEntries.pop();
  63671. this._lastUsed = Math.max(el.offset, this._lastUsed);
  63672. if (el.offset === this._firstFree) {
  63673. if (this._freeEntries.length > 0) {
  63674. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  63675. }
  63676. else {
  63677. this._firstFree += this._stride;
  63678. }
  63679. }
  63680. return el;
  63681. };
  63682. /**
  63683. * Free the element corresponding to the given element info
  63684. * @param elInfo the element that describe the allocated element
  63685. */
  63686. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  63687. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  63688. this._freeEntries.push(elInfo);
  63689. };
  63690. /**
  63691. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  63692. * 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().
  63693. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  63694. */
  63695. DynamicFloatArray.prototype.pack = function () {
  63696. // no free slot? no need to pack
  63697. if (this._freeEntries.length === 0) {
  63698. return this.buffer;
  63699. }
  63700. // If the buffer is already packed the last used will always be lower than the first free
  63701. // 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.
  63702. if (this._lastUsed < this._firstFree) {
  63703. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  63704. return elementsBuffer_1;
  63705. }
  63706. var s = this._stride;
  63707. // 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
  63708. var lastFree = new DynamicFloatArrayElementInfo();
  63709. lastFree.offset = this.totalElementCount * s;
  63710. this._freeEntries.push(lastFree);
  63711. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  63712. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  63713. var firstFreeSlotOffset = sortedFree[0].offset;
  63714. var freeZoneSize = 1;
  63715. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  63716. var prevOffset = sortedFree[0].offset;
  63717. for (var i = 1; i < sortedFree.length; i++) {
  63718. // 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
  63719. if (firstFreeSlotOffset >= occupiedZoneSize) {
  63720. break;
  63721. }
  63722. var curFree = sortedFree[i];
  63723. var curOffset = curFree.offset;
  63724. // Compute the distance between this offset and the previous
  63725. var distance = curOffset - prevOffset;
  63726. // If the distance is the stride size, they are adjacent, it good, move to the next
  63727. if (distance === s) {
  63728. // Free zone is one element bigger
  63729. ++freeZoneSize;
  63730. // as we're about to iterate to the next, the cur becomes the previous...
  63731. prevOffset = curOffset;
  63732. continue;
  63733. }
  63734. // Distance is bigger, which means there's x element between the previous free and this one
  63735. var usedRange = (distance / s) - 1;
  63736. // Two cases the free zone is smaller than the data to move or bigger
  63737. // Copy what can fit in the free zone
  63738. var curMoveOffset = curOffset - s;
  63739. var copyCount = Math.min(freeZoneSize, usedRange);
  63740. for (var j = 0; j < copyCount; j++) {
  63741. var freeI = firstFreeSlotOffset / s;
  63742. var curI = curMoveOffset / s;
  63743. var moveEl = sortedAll[curI];
  63744. this._moveElement(moveEl, firstFreeSlotOffset);
  63745. var replacedEl = sortedAll[freeI];
  63746. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  63747. replacedEl.offset = curMoveOffset;
  63748. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  63749. sortedAll[freeI] = moveEl;
  63750. sortedAll[curI] = replacedEl;
  63751. curMoveOffset -= s;
  63752. firstFreeSlotOffset += s;
  63753. }
  63754. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  63755. if (freeZoneSize <= usedRange) {
  63756. firstFreeSlotOffset = curMoveOffset + s;
  63757. freeZoneSize = 1 + copyCount;
  63758. }
  63759. else {
  63760. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  63761. }
  63762. // as we're about to iterate to the next, the cur becomes the previous...
  63763. prevOffset = curOffset;
  63764. }
  63765. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  63766. this._lastUsed = firstFreeSlotOffset - s;
  63767. this._firstFree = firstFreeSlotOffset;
  63768. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  63769. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  63770. this._allEntries = sortedAll;
  63771. return elementsBuffer;
  63772. };
  63773. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  63774. for (var i = 0; i < this._stride; i++) {
  63775. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  63776. }
  63777. element.offset = destOffset;
  63778. };
  63779. DynamicFloatArray.prototype._growBuffer = function () {
  63780. // Allocate the new buffer with 50% more entries, copy the content of the current one
  63781. var newElCount = Math.floor(this.totalElementCount * 1.5);
  63782. var newBuffer = new Float32Array(newElCount * this._stride);
  63783. newBuffer.set(this.buffer);
  63784. var curCount = this.totalElementCount;
  63785. var addedCount = newElCount - this.totalElementCount;
  63786. for (var i = 0; i < addedCount; i++) {
  63787. var element = new DynamicFloatArrayElementInfo();
  63788. element.offset = (curCount + i) * this.stride;
  63789. this._allEntries.push(element);
  63790. this._freeEntries[addedCount - i - 1] = element;
  63791. }
  63792. this._firstFree = curCount * this.stride;
  63793. this.buffer = newBuffer;
  63794. };
  63795. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  63796. /**
  63797. * Get the total count of entries that can fit in the current buffer
  63798. * @returns the elements count
  63799. */
  63800. get: function () {
  63801. return this._allEntries.length;
  63802. },
  63803. enumerable: true,
  63804. configurable: true
  63805. });
  63806. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  63807. /**
  63808. * Get the count of free entries that can still be allocated without resizing the buffer
  63809. * @returns the free elements count
  63810. */
  63811. get: function () {
  63812. return this._freeEntries.length;
  63813. },
  63814. enumerable: true,
  63815. configurable: true
  63816. });
  63817. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  63818. /**
  63819. * Get the count of allocated elements
  63820. * @returns the allocated elements count
  63821. */
  63822. get: function () {
  63823. return this._allEntries.length - this._freeEntries.length;
  63824. },
  63825. enumerable: true,
  63826. configurable: true
  63827. });
  63828. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  63829. /**
  63830. * Return the size of one element in float
  63831. * @returns the size in float
  63832. */
  63833. get: function () {
  63834. return this._stride;
  63835. },
  63836. enumerable: true,
  63837. configurable: true
  63838. });
  63839. DynamicFloatArray.prototype.sort = function () {
  63840. var _this = this;
  63841. if (!this.compareValueOffset) {
  63842. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  63843. }
  63844. var count = this.usedElementCount;
  63845. // Do we have to (re)create the sort table?
  63846. if (!this._sortTable || this._sortTable.length < count) {
  63847. // 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...
  63848. var newCount = Math.min(this.totalElementCount, count * 2);
  63849. this._sortTable = new Array(newCount);
  63850. }
  63851. if (!this._sortedTable || this._sortedTable.length !== count) {
  63852. this._sortedTable = new Array(count);
  63853. }
  63854. // Because, you know...
  63855. this.pack();
  63856. //let stride = this.stride;
  63857. //for (let i = 0; i < count; i++) {
  63858. // let si = this._sortTable[i];
  63859. // if (!si) {
  63860. // si = new SortInfo();
  63861. // this._sortTable[i] = si;
  63862. // }
  63863. // si.entry = this._allEntries[i];
  63864. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  63865. // si.swapedOffset = null;
  63866. // this._sortedTable[i] = si;
  63867. //}
  63868. var curOffset = 0;
  63869. var stride = this.stride;
  63870. for (var i = 0; i < count; i++, curOffset += stride) {
  63871. var si = this._sortTable[i];
  63872. if (!si) {
  63873. si = new SortInfo();
  63874. this._sortTable[i] = si;
  63875. }
  63876. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  63877. si.offset = curOffset;
  63878. si.swapedOffset = null;
  63879. this._sortedTable[i] = si;
  63880. }
  63881. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  63882. if (this.sortingAscending) {
  63883. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  63884. }
  63885. else {
  63886. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  63887. }
  63888. var swapElements = function (src, dst) {
  63889. for (var i = 0; i < stride; i++) {
  63890. var tps = _this.buffer[dst + i];
  63891. _this.buffer[dst + i] = _this.buffer[src + i];
  63892. _this.buffer[src + i] = tps;
  63893. }
  63894. };
  63895. // 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:
  63896. // 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),
  63897. // and I still want something with a good algorithm complexity.
  63898. // 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,
  63899. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  63900. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  63901. // 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
  63902. // until we find a SortInfo object without a swapedOffset which means we got the right location
  63903. // 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
  63904. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  63905. for (var i = 0; i < count; i++) {
  63906. // Get the element to move
  63907. var sourceSI = this._sortedTable[i];
  63908. var destSI = this._sortTable[i];
  63909. var sourceOff = sourceSI.offset;
  63910. // If the source changed location, find the new one
  63911. if (sourceSI.swapedOffset) {
  63912. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  63913. var curSI = sourceSI;
  63914. while (curSI.swapedOffset) {
  63915. curSI = this._sortTable[curSI.swapedOffset / stride];
  63916. }
  63917. // Finally get the right location
  63918. sourceOff = curSI.offset;
  63919. }
  63920. // Tag the element being replaced with its new location
  63921. destSI.swapedOffset = sourceOff;
  63922. // Swap elements (only if needed)
  63923. if (sourceOff !== destSI.offset) {
  63924. swapElements(sourceOff, destSI.offset);
  63925. }
  63926. // Update the offset in the corresponding DFAE
  63927. //sourceSI.entry.offset = destSI.entry.offset;
  63928. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  63929. }
  63930. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  63931. return true;
  63932. };
  63933. return DynamicFloatArray;
  63934. }());
  63935. BABYLON.DynamicFloatArray = DynamicFloatArray;
  63936. var SortInfo = (function () {
  63937. function SortInfo() {
  63938. this.compareData = this.offset = this.swapedOffset = null;
  63939. }
  63940. return SortInfo;
  63941. }());
  63942. })(BABYLON || (BABYLON = {}));
  63943. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  63944. var BABYLON;
  63945. (function (BABYLON) {
  63946. var Debug;
  63947. (function (Debug) {
  63948. /**
  63949. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  63950. */
  63951. var SkeletonViewer = (function () {
  63952. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  63953. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63954. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63955. this.skeleton = skeleton;
  63956. this.mesh = mesh;
  63957. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63958. this.renderingGroupId = renderingGroupId;
  63959. this.color = BABYLON.Color3.White();
  63960. this._debugLines = [];
  63961. this._isEnabled = false;
  63962. this._scene = scene;
  63963. this.update();
  63964. this._renderFunction = this.update.bind(this);
  63965. }
  63966. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63967. get: function () {
  63968. return this._isEnabled;
  63969. },
  63970. set: function (value) {
  63971. if (this._isEnabled === value) {
  63972. return;
  63973. }
  63974. this._isEnabled = value;
  63975. if (value) {
  63976. this._scene.registerBeforeRender(this._renderFunction);
  63977. }
  63978. else {
  63979. this._scene.unregisterBeforeRender(this._renderFunction);
  63980. }
  63981. },
  63982. enumerable: true,
  63983. configurable: true
  63984. });
  63985. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63986. if (x === void 0) { x = 0; }
  63987. if (y === void 0) { y = 0; }
  63988. if (z === void 0) { z = 0; }
  63989. var tmat = BABYLON.Tmp.Matrix[0];
  63990. var parentBone = bone.getParent();
  63991. tmat.copyFrom(bone.getLocalMatrix());
  63992. if (x !== 0 || y !== 0 || z !== 0) {
  63993. var tmat2 = BABYLON.Tmp.Matrix[1];
  63994. BABYLON.Matrix.IdentityToRef(tmat2);
  63995. tmat2.m[12] = x;
  63996. tmat2.m[13] = y;
  63997. tmat2.m[14] = z;
  63998. tmat2.multiplyToRef(tmat, tmat);
  63999. }
  64000. if (parentBone) {
  64001. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  64002. }
  64003. tmat.multiplyToRef(meshMat, tmat);
  64004. position.x = tmat.m[12];
  64005. position.y = tmat.m[13];
  64006. position.z = tmat.m[14];
  64007. };
  64008. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  64009. var len = bones.length;
  64010. var meshPos = this.mesh.position;
  64011. for (var i = 0; i < len; i++) {
  64012. var bone = bones[i];
  64013. var points = this._debugLines[i];
  64014. if (!points) {
  64015. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64016. this._debugLines[i] = points;
  64017. }
  64018. this._getBonePosition(points[0], bone, meshMat);
  64019. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  64020. points[0].subtractInPlace(meshPos);
  64021. points[1].subtractInPlace(meshPos);
  64022. }
  64023. };
  64024. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  64025. var len = bones.length;
  64026. var boneNum = 0;
  64027. var meshPos = this.mesh.position;
  64028. for (var i = len - 1; i >= 0; i--) {
  64029. var childBone = bones[i];
  64030. var parentBone = childBone.getParent();
  64031. if (!parentBone) {
  64032. continue;
  64033. }
  64034. var points = this._debugLines[boneNum];
  64035. if (!points) {
  64036. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64037. this._debugLines[boneNum] = points;
  64038. }
  64039. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64040. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64041. points[0].subtractInPlace(meshPos);
  64042. points[1].subtractInPlace(meshPos);
  64043. boneNum++;
  64044. }
  64045. };
  64046. SkeletonViewer.prototype.update = function () {
  64047. if (this.autoUpdateBonesMatrices) {
  64048. this.skeleton.computeAbsoluteTransforms();
  64049. }
  64050. if (this.skeleton.bones[0].length === undefined) {
  64051. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64052. }
  64053. else {
  64054. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64055. }
  64056. if (!this._debugMesh) {
  64057. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  64058. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64059. }
  64060. else {
  64061. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64062. }
  64063. this._debugMesh.position.copyFrom(this.mesh.position);
  64064. this._debugMesh.color = this.color;
  64065. };
  64066. SkeletonViewer.prototype.dispose = function () {
  64067. if (this._debugMesh) {
  64068. this.isEnabled = false;
  64069. this._debugMesh.dispose();
  64070. this._debugMesh = null;
  64071. }
  64072. };
  64073. return SkeletonViewer;
  64074. }());
  64075. Debug.SkeletonViewer = SkeletonViewer;
  64076. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64077. })(BABYLON || (BABYLON = {}));
  64078. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64079. var BABYLON;
  64080. (function (BABYLON) {
  64081. var Debug;
  64082. (function (Debug) {
  64083. var AxesViewer = (function () {
  64084. function AxesViewer(scene, scaleLines) {
  64085. if (scaleLines === void 0) { scaleLines = 1; }
  64086. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64087. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64088. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64089. this.scaleLines = 1;
  64090. this.scaleLines = scaleLines;
  64091. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64092. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64093. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64094. this._xmesh.renderingGroupId = 2;
  64095. this._ymesh.renderingGroupId = 2;
  64096. this._zmesh.renderingGroupId = 2;
  64097. this._xmesh.material.checkReadyOnlyOnce = true;
  64098. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64099. this._ymesh.material.checkReadyOnlyOnce = true;
  64100. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64101. this._zmesh.material.checkReadyOnlyOnce = true;
  64102. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64103. this.scene = scene;
  64104. }
  64105. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64106. var scaleLines = this.scaleLines;
  64107. this._xmesh.position.copyFrom(position);
  64108. this._ymesh.position.copyFrom(position);
  64109. this._zmesh.position.copyFrom(position);
  64110. var point2 = this._xline[1];
  64111. point2.x = xaxis.x * scaleLines;
  64112. point2.y = xaxis.y * scaleLines;
  64113. point2.z = xaxis.z * scaleLines;
  64114. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  64115. point2 = this._yline[1];
  64116. point2.x = yaxis.x * scaleLines;
  64117. point2.y = yaxis.y * scaleLines;
  64118. point2.z = yaxis.z * scaleLines;
  64119. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  64120. point2 = this._zline[1];
  64121. point2.x = zaxis.x * scaleLines;
  64122. point2.y = zaxis.y * scaleLines;
  64123. point2.z = zaxis.z * scaleLines;
  64124. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  64125. };
  64126. AxesViewer.prototype.dispose = function () {
  64127. if (this._xmesh) {
  64128. this._xmesh.dispose();
  64129. this._ymesh.dispose();
  64130. this._zmesh.dispose();
  64131. this._xmesh = null;
  64132. this._ymesh = null;
  64133. this._zmesh = null;
  64134. this._xline = null;
  64135. this._yline = null;
  64136. this._zline = null;
  64137. this.scene = null;
  64138. }
  64139. };
  64140. return AxesViewer;
  64141. }());
  64142. Debug.AxesViewer = AxesViewer;
  64143. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64144. })(BABYLON || (BABYLON = {}));
  64145. //# sourceMappingURL=babylon.axesViewer.js.map
  64146. var BABYLON;
  64147. (function (BABYLON) {
  64148. var Debug;
  64149. (function (Debug) {
  64150. var BoneAxesViewer = (function (_super) {
  64151. __extends(BoneAxesViewer, _super);
  64152. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64153. if (scaleLines === void 0) { scaleLines = 1; }
  64154. var _this = _super.call(this, scene, scaleLines) || this;
  64155. _this.pos = BABYLON.Vector3.Zero();
  64156. _this.xaxis = BABYLON.Vector3.Zero();
  64157. _this.yaxis = BABYLON.Vector3.Zero();
  64158. _this.zaxis = BABYLON.Vector3.Zero();
  64159. _this.mesh = mesh;
  64160. _this.bone = bone;
  64161. return _this;
  64162. }
  64163. BoneAxesViewer.prototype.update = function () {
  64164. var bone = this.bone;
  64165. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64166. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64167. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64168. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64169. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64170. };
  64171. BoneAxesViewer.prototype.dispose = function () {
  64172. if (this.pos) {
  64173. this.pos = null;
  64174. this.xaxis = null;
  64175. this.yaxis = null;
  64176. this.zaxis = null;
  64177. this.mesh = null;
  64178. this.bone = null;
  64179. _super.prototype.dispose.call(this);
  64180. }
  64181. };
  64182. return BoneAxesViewer;
  64183. }(Debug.AxesViewer));
  64184. Debug.BoneAxesViewer = BoneAxesViewer;
  64185. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64186. })(BABYLON || (BABYLON = {}));
  64187. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64188. var BABYLON;
  64189. (function (BABYLON) {
  64190. var RayHelper = (function () {
  64191. function RayHelper(ray) {
  64192. this.ray = ray;
  64193. }
  64194. RayHelper.CreateAndShow = function (ray, scene, color) {
  64195. var helper = new RayHelper(ray);
  64196. helper.show(scene, color);
  64197. return helper;
  64198. };
  64199. RayHelper.prototype.show = function (scene, color) {
  64200. if (!this._renderFunction) {
  64201. var ray = this.ray;
  64202. this._renderFunction = this._render.bind(this);
  64203. this._scene = scene;
  64204. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64205. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64206. this._scene.registerBeforeRender(this._renderFunction);
  64207. }
  64208. if (color) {
  64209. this._renderLine.color.copyFrom(color);
  64210. }
  64211. };
  64212. RayHelper.prototype.hide = function () {
  64213. if (this._renderFunction) {
  64214. this._scene.unregisterBeforeRender(this._renderFunction);
  64215. this._scene = null;
  64216. this._renderFunction = null;
  64217. this._renderLine.dispose();
  64218. this._renderLine = null;
  64219. this._renderPoints = null;
  64220. }
  64221. };
  64222. RayHelper.prototype._render = function () {
  64223. var ray = this.ray;
  64224. var point = this._renderPoints[1];
  64225. var len = Math.min(ray.length, 1000000);
  64226. point.copyFrom(ray.direction);
  64227. point.scaleInPlace(len);
  64228. point.addInPlace(ray.origin);
  64229. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64230. };
  64231. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64232. this._attachedToMesh = mesh;
  64233. var ray = this.ray;
  64234. if (!ray.direction) {
  64235. ray.direction = BABYLON.Vector3.Zero();
  64236. }
  64237. if (!ray.origin) {
  64238. ray.origin = BABYLON.Vector3.Zero();
  64239. }
  64240. if (length) {
  64241. ray.length = length;
  64242. }
  64243. if (!meshSpaceOrigin) {
  64244. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64245. }
  64246. if (!meshSpaceDirection) {
  64247. // -1 so that this will work with Mesh.lookAt
  64248. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64249. }
  64250. if (!this._meshSpaceDirection) {
  64251. this._meshSpaceDirection = meshSpaceDirection.clone();
  64252. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64253. }
  64254. else {
  64255. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64256. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64257. }
  64258. if (!this._updateToMeshFunction) {
  64259. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64260. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64261. }
  64262. this._updateToMesh();
  64263. };
  64264. RayHelper.prototype.detachFromMesh = function () {
  64265. if (this._attachedToMesh) {
  64266. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64267. this._attachedToMesh = null;
  64268. this._updateToMeshFunction = null;
  64269. }
  64270. };
  64271. RayHelper.prototype._updateToMesh = function () {
  64272. var ray = this.ray;
  64273. if (this._attachedToMesh._isDisposed) {
  64274. this.detachFromMesh();
  64275. return;
  64276. }
  64277. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64278. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64279. };
  64280. RayHelper.prototype.dispose = function () {
  64281. this.hide();
  64282. this.detachFromMesh();
  64283. this.ray = null;
  64284. };
  64285. return RayHelper;
  64286. }());
  64287. BABYLON.RayHelper = RayHelper;
  64288. })(BABYLON || (BABYLON = {}));
  64289. //# sourceMappingURL=babylon.rayHelper.js.map
  64290. var BABYLON;
  64291. (function (BABYLON) {
  64292. var DebugLayer = (function () {
  64293. function DebugLayer(scene) {
  64294. this._scene = scene;
  64295. }
  64296. /** Creates the inspector window. */
  64297. DebugLayer.prototype._createInspector = function (config) {
  64298. if (config === void 0) { config = {}; }
  64299. var popup = config.popup || false;
  64300. var initialTab = config.initialTab || 0;
  64301. var parentElement = config.parentElement || null;
  64302. if (!this._inspector) {
  64303. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64304. } // else nothing to do,; instance is already existing
  64305. };
  64306. DebugLayer.prototype.isVisible = function () {
  64307. if (!this._inspector) {
  64308. return false;
  64309. }
  64310. return true;
  64311. };
  64312. DebugLayer.prototype.hide = function () {
  64313. if (this._inspector) {
  64314. try {
  64315. this._inspector.dispose();
  64316. }
  64317. catch (e) {
  64318. // If the inspector has been removed directly from the inspector tool
  64319. }
  64320. this._inspector = null;
  64321. }
  64322. };
  64323. DebugLayer.prototype.show = function (config) {
  64324. if (config === void 0) { config = {}; }
  64325. if (typeof INSPECTOR == 'undefined') {
  64326. // Load inspector and add it to the DOM
  64327. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64328. }
  64329. else {
  64330. // Otherwise creates the inspector
  64331. this._createInspector(config);
  64332. }
  64333. };
  64334. // Get protocol used - http or https
  64335. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64336. return DebugLayer;
  64337. }());
  64338. BABYLON.DebugLayer = DebugLayer;
  64339. })(BABYLON || (BABYLON = {}));
  64340. //# sourceMappingURL=babylon.debugLayer.js.map
  64341. var BABYLON;
  64342. (function (BABYLON) {
  64343. var Debug;
  64344. (function (Debug) {
  64345. var PhysicsViewer = (function () {
  64346. function PhysicsViewer(scene) {
  64347. this._impostors = [];
  64348. this._meshes = [];
  64349. this._numMeshes = 0;
  64350. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64351. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  64352. }
  64353. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64354. var plugin = this._physicsEnginePlugin;
  64355. for (var i = 0; i < this._numMeshes; i++) {
  64356. if (this._impostors[i].isDisposed) {
  64357. this.hideImpostor(this._impostors[i--]);
  64358. }
  64359. else {
  64360. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  64361. }
  64362. }
  64363. };
  64364. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64365. for (var i = 0; i < this._numMeshes; i++) {
  64366. if (this._impostors[i] == impostor) {
  64367. return;
  64368. }
  64369. }
  64370. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64371. if (debugMesh) {
  64372. this._impostors[this._numMeshes] = impostor;
  64373. this._meshes[this._numMeshes] = debugMesh;
  64374. if (this._numMeshes === 0) {
  64375. this._renderFunction = this._updateDebugMeshes.bind(this);
  64376. this._scene.registerBeforeRender(this._renderFunction);
  64377. }
  64378. this._numMeshes++;
  64379. }
  64380. };
  64381. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64382. var removed = false;
  64383. for (var i = 0; i < this._numMeshes; i++) {
  64384. if (this._impostors[i] == impostor) {
  64385. this._scene.removeMesh(this._meshes[i]);
  64386. this._meshes[i].dispose();
  64387. this._numMeshes--;
  64388. if (this._numMeshes > 0) {
  64389. this._meshes[i] = this._meshes[this._numMeshes];
  64390. this._impostors[i] = this._impostors[this._numMeshes];
  64391. this._meshes[this._numMeshes] = null;
  64392. this._impostors[this._numMeshes] = null;
  64393. }
  64394. else {
  64395. this._meshes[0] = null;
  64396. this._impostors[0] = null;
  64397. }
  64398. removed = true;
  64399. break;
  64400. }
  64401. }
  64402. if (removed && this._numMeshes === 0) {
  64403. this._scene.unregisterBeforeRender(this._renderFunction);
  64404. }
  64405. };
  64406. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64407. if (!this._debugMaterial) {
  64408. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64409. this._debugMaterial.wireframe = true;
  64410. }
  64411. return this._debugMaterial;
  64412. };
  64413. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64414. if (!this._debugBoxMesh) {
  64415. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64416. this._debugBoxMesh.renderingGroupId = 1;
  64417. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64418. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64419. scene.removeMesh(this._debugBoxMesh);
  64420. }
  64421. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64422. };
  64423. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64424. if (!this._debugSphereMesh) {
  64425. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64426. this._debugSphereMesh.renderingGroupId = 1;
  64427. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64428. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64429. scene.removeMesh(this._debugSphereMesh);
  64430. }
  64431. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64432. };
  64433. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64434. var body = impostor.physicsBody;
  64435. var shape = body.shapes[0];
  64436. var mesh;
  64437. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64438. mesh = this._getDebugBoxMesh(scene);
  64439. impostor.getBoxSizeToRef(mesh.scaling);
  64440. }
  64441. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64442. mesh = this._getDebugSphereMesh(scene);
  64443. var radius = impostor.getRadius();
  64444. mesh.scaling.x = radius * 2;
  64445. mesh.scaling.y = radius * 2;
  64446. mesh.scaling.z = radius * 2;
  64447. }
  64448. return mesh;
  64449. };
  64450. PhysicsViewer.prototype.dispose = function () {
  64451. for (var i = 0; i < this._numMeshes; i++) {
  64452. this.hideImpostor(this._impostors[i]);
  64453. }
  64454. if (this._debugBoxMesh) {
  64455. this._debugBoxMesh.dispose();
  64456. }
  64457. if (this._debugSphereMesh) {
  64458. this._debugSphereMesh.dispose();
  64459. }
  64460. if (this._debugMaterial) {
  64461. this._debugMaterial.dispose();
  64462. }
  64463. this._impostors.length = 0;
  64464. this._scene = null;
  64465. this._physicsEnginePlugin = null;
  64466. };
  64467. return PhysicsViewer;
  64468. }());
  64469. Debug.PhysicsViewer = PhysicsViewer;
  64470. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64471. })(BABYLON || (BABYLON = {}));
  64472. //# sourceMappingURL=babylon.physicsViewer.js.map
  64473. var BABYLON;
  64474. (function (BABYLON) {
  64475. var BoundingBoxRenderer = (function () {
  64476. function BoundingBoxRenderer(scene) {
  64477. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64478. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64479. this.showBackLines = true;
  64480. this.renderList = new BABYLON.SmartArray(32);
  64481. this._vertexBuffers = {};
  64482. this._scene = scene;
  64483. }
  64484. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64485. if (this._colorShader) {
  64486. return;
  64487. }
  64488. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  64489. attributes: [BABYLON.VertexBuffer.PositionKind],
  64490. uniforms: ["world", "viewProjection", "color"]
  64491. });
  64492. var engine = this._scene.getEngine();
  64493. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64494. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64495. this._createIndexBuffer();
  64496. };
  64497. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64498. var engine = this._scene.getEngine();
  64499. 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]);
  64500. };
  64501. BoundingBoxRenderer.prototype._rebuild = function () {
  64502. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  64503. this._createIndexBuffer();
  64504. };
  64505. BoundingBoxRenderer.prototype.reset = function () {
  64506. this.renderList.reset();
  64507. };
  64508. BoundingBoxRenderer.prototype.render = function () {
  64509. if (this.renderList.length === 0) {
  64510. return;
  64511. }
  64512. this._prepareRessources();
  64513. if (!this._colorShader.isReady()) {
  64514. return;
  64515. }
  64516. var engine = this._scene.getEngine();
  64517. engine.setDepthWrite(false);
  64518. this._colorShader._preBind();
  64519. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64520. var boundingBox = this.renderList.data[boundingBoxIndex];
  64521. var min = boundingBox.minimum;
  64522. var max = boundingBox.maximum;
  64523. var diff = max.subtract(min);
  64524. var median = min.add(diff.scale(0.5));
  64525. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64526. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64527. .multiply(boundingBox.getWorldMatrix());
  64528. // VBOs
  64529. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64530. if (this.showBackLines) {
  64531. // Back
  64532. engine.setDepthFunctionToGreaterOrEqual();
  64533. this._scene.resetCachedMaterial();
  64534. this._colorShader.setColor4("color", this.backColor.toColor4());
  64535. this._colorShader.bind(worldMatrix);
  64536. // Draw order
  64537. engine.draw(false, 0, 24);
  64538. }
  64539. // Front
  64540. engine.setDepthFunctionToLess();
  64541. this._scene.resetCachedMaterial();
  64542. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64543. this._colorShader.bind(worldMatrix);
  64544. // Draw order
  64545. engine.draw(false, 0, 24);
  64546. }
  64547. this._colorShader.unbind();
  64548. engine.setDepthFunctionToLessOrEqual();
  64549. engine.setDepthWrite(true);
  64550. };
  64551. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64552. this._prepareRessources();
  64553. if (!this._colorShader.isReady()) {
  64554. return;
  64555. }
  64556. var engine = this._scene.getEngine();
  64557. engine.setDepthWrite(false);
  64558. engine.setColorWrite(false);
  64559. this._colorShader._preBind();
  64560. var boundingBox = mesh._boundingInfo.boundingBox;
  64561. var min = boundingBox.minimum;
  64562. var max = boundingBox.maximum;
  64563. var diff = max.subtract(min);
  64564. var median = min.add(diff.scale(0.5));
  64565. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64566. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64567. .multiply(boundingBox.getWorldMatrix());
  64568. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64569. engine.setDepthFunctionToLess();
  64570. this._scene.resetCachedMaterial();
  64571. this._colorShader.bind(worldMatrix);
  64572. engine.draw(false, 0, 24);
  64573. this._colorShader.unbind();
  64574. engine.setDepthFunctionToLessOrEqual();
  64575. engine.setDepthWrite(true);
  64576. engine.setColorWrite(true);
  64577. };
  64578. BoundingBoxRenderer.prototype.dispose = function () {
  64579. if (!this._colorShader) {
  64580. return;
  64581. }
  64582. this.renderList.dispose();
  64583. this._colorShader.dispose();
  64584. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64585. if (buffer) {
  64586. buffer.dispose();
  64587. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64588. }
  64589. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64590. };
  64591. return BoundingBoxRenderer;
  64592. }());
  64593. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64594. })(BABYLON || (BABYLON = {}));
  64595. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64596. var BABYLON;
  64597. (function (BABYLON) {
  64598. var MorphTarget = (function () {
  64599. function MorphTarget(name, influence) {
  64600. if (influence === void 0) { influence = 0; }
  64601. this.name = name;
  64602. this.animations = new Array();
  64603. this.onInfluenceChanged = new BABYLON.Observable();
  64604. this.influence = influence;
  64605. }
  64606. Object.defineProperty(MorphTarget.prototype, "influence", {
  64607. get: function () {
  64608. return this._influence;
  64609. },
  64610. set: function (influence) {
  64611. if (this._influence === influence) {
  64612. return;
  64613. }
  64614. var previous = this._influence;
  64615. this._influence = influence;
  64616. if (this.onInfluenceChanged.hasObservers) {
  64617. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  64618. }
  64619. },
  64620. enumerable: true,
  64621. configurable: true
  64622. });
  64623. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  64624. get: function () {
  64625. return this._normals !== undefined;
  64626. },
  64627. enumerable: true,
  64628. configurable: true
  64629. });
  64630. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  64631. get: function () {
  64632. return this._tangents !== undefined;
  64633. },
  64634. enumerable: true,
  64635. configurable: true
  64636. });
  64637. MorphTarget.prototype.setPositions = function (data) {
  64638. this._positions = new Float32Array(data);
  64639. };
  64640. MorphTarget.prototype.getPositions = function () {
  64641. return this._positions;
  64642. };
  64643. MorphTarget.prototype.setNormals = function (data) {
  64644. this._normals = new Float32Array(data);
  64645. };
  64646. MorphTarget.prototype.getNormals = function () {
  64647. return this._normals;
  64648. };
  64649. MorphTarget.prototype.setTangents = function (data) {
  64650. this._tangents = new Float32Array(data);
  64651. };
  64652. MorphTarget.prototype.getTangents = function () {
  64653. return this._tangents;
  64654. };
  64655. /**
  64656. * Serializes the current target into a Serialization object.
  64657. * Returns the serialized object.
  64658. */
  64659. MorphTarget.prototype.serialize = function () {
  64660. var serializationObject = {};
  64661. serializationObject.name = this.name;
  64662. serializationObject.influence = this.influence;
  64663. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  64664. if (this.hasNormals) {
  64665. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  64666. }
  64667. if (this.hasTangents) {
  64668. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  64669. }
  64670. return serializationObject;
  64671. };
  64672. // Statics
  64673. MorphTarget.Parse = function (serializationObject) {
  64674. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  64675. result.setPositions(serializationObject.positions);
  64676. if (serializationObject.normals) {
  64677. result.setNormals(serializationObject.normals);
  64678. }
  64679. if (serializationObject.tangents) {
  64680. result.setTangents(serializationObject.tangents);
  64681. }
  64682. return result;
  64683. };
  64684. MorphTarget.FromMesh = function (mesh, name, influence) {
  64685. if (!name) {
  64686. name = mesh.name;
  64687. }
  64688. var result = new MorphTarget(name, influence);
  64689. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  64690. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64691. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  64692. }
  64693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  64694. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  64695. }
  64696. return result;
  64697. };
  64698. return MorphTarget;
  64699. }());
  64700. BABYLON.MorphTarget = MorphTarget;
  64701. })(BABYLON || (BABYLON = {}));
  64702. //# sourceMappingURL=babylon.morphTarget.js.map
  64703. var BABYLON;
  64704. (function (BABYLON) {
  64705. var MorphTargetManager = (function () {
  64706. function MorphTargetManager(scene) {
  64707. this._targets = new Array();
  64708. this._targetObservable = new Array();
  64709. this._activeTargets = new BABYLON.SmartArray(16);
  64710. this._supportsNormals = false;
  64711. this._supportsTangents = false;
  64712. this._vertexCount = 0;
  64713. this._uniqueId = 0;
  64714. this._tempInfluences = new Array();
  64715. if (!scene) {
  64716. scene = BABYLON.Engine.LastCreatedScene;
  64717. }
  64718. this._scene = scene;
  64719. this._scene.morphTargetManagers.push(this);
  64720. this._uniqueId = scene.getUniqueId();
  64721. }
  64722. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  64723. get: function () {
  64724. return this._uniqueId;
  64725. },
  64726. enumerable: true,
  64727. configurable: true
  64728. });
  64729. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  64730. get: function () {
  64731. return this._vertexCount;
  64732. },
  64733. enumerable: true,
  64734. configurable: true
  64735. });
  64736. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  64737. get: function () {
  64738. return this._supportsNormals;
  64739. },
  64740. enumerable: true,
  64741. configurable: true
  64742. });
  64743. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  64744. get: function () {
  64745. return this._supportsTangents;
  64746. },
  64747. enumerable: true,
  64748. configurable: true
  64749. });
  64750. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  64751. get: function () {
  64752. return this._targets.length;
  64753. },
  64754. enumerable: true,
  64755. configurable: true
  64756. });
  64757. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  64758. get: function () {
  64759. return this._activeTargets.length;
  64760. },
  64761. enumerable: true,
  64762. configurable: true
  64763. });
  64764. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  64765. get: function () {
  64766. return this._influences;
  64767. },
  64768. enumerable: true,
  64769. configurable: true
  64770. });
  64771. MorphTargetManager.prototype.getActiveTarget = function (index) {
  64772. return this._activeTargets.data[index];
  64773. };
  64774. MorphTargetManager.prototype.getTarget = function (index) {
  64775. return this._targets[index];
  64776. };
  64777. MorphTargetManager.prototype.addTarget = function (target) {
  64778. var _this = this;
  64779. if (this._vertexCount) {
  64780. if (this._vertexCount !== target.getPositions().length / 3) {
  64781. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  64782. return;
  64783. }
  64784. }
  64785. this._targets.push(target);
  64786. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  64787. _this._syncActiveTargets(needUpdate);
  64788. }));
  64789. this._syncActiveTargets(true);
  64790. };
  64791. MorphTargetManager.prototype.removeTarget = function (target) {
  64792. var index = this._targets.indexOf(target);
  64793. if (index >= 0) {
  64794. this._targets.splice(index, 1);
  64795. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  64796. this._vertexCount = 0;
  64797. this._syncActiveTargets(true);
  64798. }
  64799. };
  64800. /**
  64801. * Serializes the current manager into a Serialization object.
  64802. * Returns the serialized object.
  64803. */
  64804. MorphTargetManager.prototype.serialize = function () {
  64805. var serializationObject = {};
  64806. serializationObject.id = this.uniqueId;
  64807. serializationObject.targets = [];
  64808. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  64809. var target = _a[_i];
  64810. serializationObject.targets.push(target.serialize());
  64811. }
  64812. return serializationObject;
  64813. };
  64814. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  64815. this._syncActiveTargets(needUpdate);
  64816. };
  64817. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  64818. var influenceCount = 0;
  64819. this._activeTargets.reset();
  64820. this._supportsNormals = true;
  64821. this._supportsTangents = true;
  64822. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  64823. var target = _a[_i];
  64824. if (target.influence > 0) {
  64825. this._activeTargets.push(target);
  64826. this._tempInfluences[influenceCount++] = target.influence;
  64827. this._supportsNormals = this._supportsNormals && target.hasNormals;
  64828. this._supportsTangents = this._supportsTangents && target.hasTangents;
  64829. if (this._vertexCount === 0) {
  64830. this._vertexCount = target.getPositions().length / 3;
  64831. }
  64832. }
  64833. }
  64834. if (!this._influences || this._influences.length !== influenceCount) {
  64835. this._influences = new Float32Array(influenceCount);
  64836. }
  64837. for (var index = 0; index < influenceCount; index++) {
  64838. this._influences[index] = this._tempInfluences[index];
  64839. }
  64840. if (needUpdate) {
  64841. // Flag meshes as dirty to resync with the active targets
  64842. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  64843. var mesh = _c[_b];
  64844. if (mesh.morphTargetManager === this) {
  64845. mesh._syncGeometryWithMorphTargetManager();
  64846. }
  64847. }
  64848. }
  64849. };
  64850. // Statics
  64851. MorphTargetManager.Parse = function (serializationObject, scene) {
  64852. var result = new MorphTargetManager(scene);
  64853. result._uniqueId = serializationObject.id;
  64854. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  64855. var targetData = _a[_i];
  64856. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  64857. }
  64858. return result;
  64859. };
  64860. return MorphTargetManager;
  64861. }());
  64862. BABYLON.MorphTargetManager = MorphTargetManager;
  64863. })(BABYLON || (BABYLON = {}));
  64864. //# sourceMappingURL=babylon.morphTargetManager.js.map
  64865. var BABYLON;
  64866. (function (BABYLON) {
  64867. /**
  64868. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  64869. * It can help converting any input color in a desired output one. This can then be used to create effects
  64870. * from sepia, black and white to sixties or futuristic rendering...
  64871. *
  64872. * The only supported format is currently 3dl.
  64873. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  64874. */
  64875. var ColorGradingTexture = (function (_super) {
  64876. __extends(ColorGradingTexture, _super);
  64877. /**
  64878. * Instantiates a ColorGradingTexture from the following parameters.
  64879. *
  64880. * @param url The location of the color gradind data (currently only supporting 3dl)
  64881. * @param scene The scene the texture will be used in
  64882. */
  64883. function ColorGradingTexture(url, scene) {
  64884. var _this = _super.call(this, scene) || this;
  64885. if (!url) {
  64886. return _this;
  64887. }
  64888. _this._textureMatrix = BABYLON.Matrix.Identity();
  64889. _this.name = url;
  64890. _this.url = url;
  64891. _this.hasAlpha = false;
  64892. _this.isCube = false;
  64893. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64894. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64895. _this.anisotropicFilteringLevel = 1;
  64896. _this._texture = _this._getFromCache(url, true);
  64897. if (!_this._texture) {
  64898. if (!scene.useDelayedTextureLoading) {
  64899. _this.loadTexture();
  64900. }
  64901. else {
  64902. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64903. }
  64904. }
  64905. return _this;
  64906. }
  64907. /**
  64908. * Returns the texture matrix used in most of the material.
  64909. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  64910. */
  64911. ColorGradingTexture.prototype.getTextureMatrix = function () {
  64912. return this._textureMatrix;
  64913. };
  64914. /**
  64915. * Occurs when the file being loaded is a .3dl LUT file.
  64916. */
  64917. ColorGradingTexture.prototype.load3dlTexture = function () {
  64918. var _this = this;
  64919. var mipLevels = 0;
  64920. var floatArrayView = null;
  64921. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64922. this._texture = texture;
  64923. var callback = function (text) {
  64924. var data;
  64925. var tempData;
  64926. var line;
  64927. var lines = text.split('\n');
  64928. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  64929. var maxColor = 0;
  64930. for (var i = 0; i < lines.length; i++) {
  64931. line = lines[i];
  64932. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  64933. continue;
  64934. if (line.indexOf('#') === 0)
  64935. continue;
  64936. var words = line.split(" ");
  64937. if (size === 0) {
  64938. // Number of space + one
  64939. size = words.length;
  64940. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  64941. tempData = new Float32Array(size * size * size * 4);
  64942. continue;
  64943. }
  64944. if (size != 0) {
  64945. var r = Math.max(parseInt(words[0]), 0);
  64946. var g = Math.max(parseInt(words[1]), 0);
  64947. var b = Math.max(parseInt(words[2]), 0);
  64948. maxColor = Math.max(r, maxColor);
  64949. maxColor = Math.max(g, maxColor);
  64950. maxColor = Math.max(b, maxColor);
  64951. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  64952. tempData[pixelStorageIndex + 0] = r;
  64953. tempData[pixelStorageIndex + 1] = g;
  64954. tempData[pixelStorageIndex + 2] = b;
  64955. pixelIndexSlice++;
  64956. if (pixelIndexSlice % size == 0) {
  64957. pixelIndexH++;
  64958. pixelIndexSlice = 0;
  64959. if (pixelIndexH % size == 0) {
  64960. pixelIndexW++;
  64961. pixelIndexH = 0;
  64962. }
  64963. }
  64964. }
  64965. }
  64966. for (var i = 0; i < tempData.length; i++) {
  64967. if (i > 0 && (i + 1) % 4 === 0) {
  64968. data[i] = 255;
  64969. }
  64970. else {
  64971. var value = tempData[i];
  64972. data[i] = (value / maxColor * 255);
  64973. }
  64974. }
  64975. texture.updateSize(size * size, size);
  64976. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  64977. };
  64978. BABYLON.Tools.LoadFile(this.url, callback);
  64979. return this._texture;
  64980. };
  64981. /**
  64982. * Starts the loading process of the texture.
  64983. */
  64984. ColorGradingTexture.prototype.loadTexture = function () {
  64985. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  64986. this.load3dlTexture();
  64987. }
  64988. };
  64989. /**
  64990. * Clones the color gradind texture.
  64991. */
  64992. ColorGradingTexture.prototype.clone = function () {
  64993. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  64994. // Base texture
  64995. newTexture.level = this.level;
  64996. return newTexture;
  64997. };
  64998. /**
  64999. * Called during delayed load for textures.
  65000. */
  65001. ColorGradingTexture.prototype.delayLoad = function () {
  65002. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65003. return;
  65004. }
  65005. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65006. this._texture = this._getFromCache(this.url, true);
  65007. if (!this._texture) {
  65008. this.loadTexture();
  65009. }
  65010. };
  65011. /**
  65012. * Parses a color grading texture serialized by Babylon.
  65013. * @param parsedTexture The texture information being parsedTexture
  65014. * @param scene The scene to load the texture in
  65015. * @param rootUrl The root url of the data assets to load
  65016. * @return A color gradind texture
  65017. */
  65018. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65019. var texture = null;
  65020. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  65021. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  65022. texture.name = parsedTexture.name;
  65023. texture.level = parsedTexture.level;
  65024. }
  65025. return texture;
  65026. };
  65027. /**
  65028. * Serializes the LUT texture to json format.
  65029. */
  65030. ColorGradingTexture.prototype.serialize = function () {
  65031. if (!this.name) {
  65032. return null;
  65033. }
  65034. var serializationObject = {};
  65035. serializationObject.name = this.name;
  65036. serializationObject.level = this.level;
  65037. serializationObject.customType = "BABYLON.ColorGradingTexture";
  65038. return serializationObject;
  65039. };
  65040. /**
  65041. * Empty line regex stored for GC.
  65042. */
  65043. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  65044. return ColorGradingTexture;
  65045. }(BABYLON.BaseTexture));
  65046. BABYLON.ColorGradingTexture = ColorGradingTexture;
  65047. })(BABYLON || (BABYLON = {}));
  65048. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  65049. var BABYLON;
  65050. (function (BABYLON) {
  65051. /**
  65052. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  65053. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  65054. * 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;
  65055. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  65056. */
  65057. var ColorCurves = (function () {
  65058. function ColorCurves() {
  65059. this._dirty = true;
  65060. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  65061. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  65062. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  65063. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  65064. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  65065. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  65066. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  65067. this._globalHue = 30;
  65068. this._globalDensity = 0;
  65069. this._globalSaturation = 0;
  65070. this._globalExposure = 0;
  65071. this._highlightsHue = 30;
  65072. this._highlightsDensity = 0;
  65073. this._highlightsSaturation = 0;
  65074. this._highlightsExposure = 0;
  65075. this._midtonesHue = 30;
  65076. this._midtonesDensity = 0;
  65077. this._midtonesSaturation = 0;
  65078. this._midtonesExposure = 0;
  65079. this._shadowsHue = 30;
  65080. this._shadowsDensity = 0;
  65081. this._shadowsSaturation = 0;
  65082. this._shadowsExposure = 0;
  65083. }
  65084. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  65085. /**
  65086. * Gets the global Hue value.
  65087. * 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).
  65088. */
  65089. get: function () {
  65090. return this._globalHue;
  65091. },
  65092. /**
  65093. * Sets the global Hue value.
  65094. * 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).
  65095. */
  65096. set: function (value) {
  65097. this._globalHue = value;
  65098. this._dirty = true;
  65099. },
  65100. enumerable: true,
  65101. configurable: true
  65102. });
  65103. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  65104. /**
  65105. * Gets the global Density value.
  65106. * 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.
  65107. * Values less than zero provide a filter of opposite hue.
  65108. */
  65109. get: function () {
  65110. return this._globalDensity;
  65111. },
  65112. /**
  65113. * Sets the global Density value.
  65114. * 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.
  65115. * Values less than zero provide a filter of opposite hue.
  65116. */
  65117. set: function (value) {
  65118. this._globalDensity = value;
  65119. this._dirty = true;
  65120. },
  65121. enumerable: true,
  65122. configurable: true
  65123. });
  65124. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  65125. /**
  65126. * Gets the global Saturation value.
  65127. * 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.
  65128. */
  65129. get: function () {
  65130. return this._globalSaturation;
  65131. },
  65132. /**
  65133. * Sets the global Saturation value.
  65134. * 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.
  65135. */
  65136. set: function (value) {
  65137. this._globalSaturation = value;
  65138. this._dirty = true;
  65139. },
  65140. enumerable: true,
  65141. configurable: true
  65142. });
  65143. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  65144. /**
  65145. * Gets the highlights Hue value.
  65146. * 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).
  65147. */
  65148. get: function () {
  65149. return this._highlightsHue;
  65150. },
  65151. /**
  65152. * Sets the highlights Hue value.
  65153. * 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).
  65154. */
  65155. set: function (value) {
  65156. this._highlightsHue = value;
  65157. this._dirty = true;
  65158. },
  65159. enumerable: true,
  65160. configurable: true
  65161. });
  65162. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  65163. /**
  65164. * Gets the highlights Density value.
  65165. * 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.
  65166. * Values less than zero provide a filter of opposite hue.
  65167. */
  65168. get: function () {
  65169. return this._highlightsDensity;
  65170. },
  65171. /**
  65172. * Sets the highlights Density value.
  65173. * 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.
  65174. * Values less than zero provide a filter of opposite hue.
  65175. */
  65176. set: function (value) {
  65177. this._highlightsDensity = value;
  65178. this._dirty = true;
  65179. },
  65180. enumerable: true,
  65181. configurable: true
  65182. });
  65183. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  65184. /**
  65185. * Gets the highlights Saturation value.
  65186. * 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.
  65187. */
  65188. get: function () {
  65189. return this._highlightsSaturation;
  65190. },
  65191. /**
  65192. * Sets the highlights Saturation value.
  65193. * 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.
  65194. */
  65195. set: function (value) {
  65196. this._highlightsSaturation = value;
  65197. this._dirty = true;
  65198. },
  65199. enumerable: true,
  65200. configurable: true
  65201. });
  65202. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  65203. /**
  65204. * Gets the highlights Exposure value.
  65205. * 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.
  65206. */
  65207. get: function () {
  65208. return this._highlightsExposure;
  65209. },
  65210. /**
  65211. * Sets the highlights Exposure value.
  65212. * 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.
  65213. */
  65214. set: function (value) {
  65215. this._highlightsExposure = value;
  65216. this._dirty = true;
  65217. },
  65218. enumerable: true,
  65219. configurable: true
  65220. });
  65221. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  65222. /**
  65223. * Gets the midtones Hue value.
  65224. * 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).
  65225. */
  65226. get: function () {
  65227. return this._midtonesHue;
  65228. },
  65229. /**
  65230. * Sets the midtones Hue value.
  65231. * 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).
  65232. */
  65233. set: function (value) {
  65234. this._midtonesHue = value;
  65235. this._dirty = true;
  65236. },
  65237. enumerable: true,
  65238. configurable: true
  65239. });
  65240. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  65241. /**
  65242. * Gets the midtones Density value.
  65243. * 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.
  65244. * Values less than zero provide a filter of opposite hue.
  65245. */
  65246. get: function () {
  65247. return this._midtonesDensity;
  65248. },
  65249. /**
  65250. * Sets the midtones Density value.
  65251. * 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.
  65252. * Values less than zero provide a filter of opposite hue.
  65253. */
  65254. set: function (value) {
  65255. this._midtonesDensity = value;
  65256. this._dirty = true;
  65257. },
  65258. enumerable: true,
  65259. configurable: true
  65260. });
  65261. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  65262. /**
  65263. * Gets the midtones Saturation value.
  65264. * 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.
  65265. */
  65266. get: function () {
  65267. return this._midtonesSaturation;
  65268. },
  65269. /**
  65270. * Sets the midtones Saturation value.
  65271. * 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.
  65272. */
  65273. set: function (value) {
  65274. this._midtonesSaturation = value;
  65275. this._dirty = true;
  65276. },
  65277. enumerable: true,
  65278. configurable: true
  65279. });
  65280. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  65281. /**
  65282. * Gets the midtones Exposure value.
  65283. * 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.
  65284. */
  65285. get: function () {
  65286. return this._midtonesExposure;
  65287. },
  65288. /**
  65289. * Sets the midtones Exposure value.
  65290. * 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.
  65291. */
  65292. set: function (value) {
  65293. this._midtonesExposure = value;
  65294. this._dirty = true;
  65295. },
  65296. enumerable: true,
  65297. configurable: true
  65298. });
  65299. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  65300. /**
  65301. * Gets the shadows Hue value.
  65302. * 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).
  65303. */
  65304. get: function () {
  65305. return this._shadowsHue;
  65306. },
  65307. /**
  65308. * Sets the shadows Hue value.
  65309. * 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).
  65310. */
  65311. set: function (value) {
  65312. this._shadowsHue = value;
  65313. this._dirty = true;
  65314. },
  65315. enumerable: true,
  65316. configurable: true
  65317. });
  65318. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  65319. /**
  65320. * Gets the shadows Density value.
  65321. * 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.
  65322. * Values less than zero provide a filter of opposite hue.
  65323. */
  65324. get: function () {
  65325. return this._shadowsDensity;
  65326. },
  65327. /**
  65328. * Sets the shadows Density value.
  65329. * 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.
  65330. * Values less than zero provide a filter of opposite hue.
  65331. */
  65332. set: function (value) {
  65333. this._shadowsDensity = value;
  65334. this._dirty = true;
  65335. },
  65336. enumerable: true,
  65337. configurable: true
  65338. });
  65339. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  65340. /**
  65341. * Gets the shadows Saturation value.
  65342. * 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.
  65343. */
  65344. get: function () {
  65345. return this._shadowsSaturation;
  65346. },
  65347. /**
  65348. * Sets the shadows Saturation value.
  65349. * 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.
  65350. */
  65351. set: function (value) {
  65352. this._shadowsSaturation = value;
  65353. this._dirty = true;
  65354. },
  65355. enumerable: true,
  65356. configurable: true
  65357. });
  65358. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  65359. /**
  65360. * Gets the shadows Exposure value.
  65361. * 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.
  65362. */
  65363. get: function () {
  65364. return this._shadowsExposure;
  65365. },
  65366. /**
  65367. * Sets the shadows Exposure value.
  65368. * 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.
  65369. */
  65370. set: function (value) {
  65371. this._shadowsExposure = value;
  65372. this._dirty = true;
  65373. },
  65374. enumerable: true,
  65375. configurable: true
  65376. });
  65377. ColorCurves.prototype.getClassName = function () {
  65378. return "ColorCurves";
  65379. };
  65380. /**
  65381. * Binds the color curves to the shader.
  65382. * @param colorCurves The color curve to bind
  65383. * @param effect The effect to bind to
  65384. */
  65385. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  65386. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  65387. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  65388. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  65389. if (colorCurves._dirty) {
  65390. colorCurves._dirty = false;
  65391. // Fill in global info.
  65392. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  65393. // Compute highlights info.
  65394. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  65395. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  65396. // Compute midtones info.
  65397. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  65398. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  65399. // Compute shadows info.
  65400. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  65401. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  65402. // Compute deltas (neutral is midtones).
  65403. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  65404. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  65405. }
  65406. if (effect) {
  65407. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  65408. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  65409. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  65410. }
  65411. };
  65412. /**
  65413. * Prepare the list of uniforms associated with the ColorCurves effects.
  65414. * @param uniformsList The list of uniforms used in the effect
  65415. */
  65416. ColorCurves.PrepareUniforms = function (uniformsList) {
  65417. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  65418. };
  65419. /**
  65420. * Returns color grading data based on a hue, density, saturation and exposure value.
  65421. * @param filterHue The hue of the color filter.
  65422. * @param filterDensity The density of the color filter.
  65423. * @param saturation The saturation.
  65424. * @param exposure The exposure.
  65425. * @param result The result data container.
  65426. */
  65427. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  65428. if (hue == null) {
  65429. return;
  65430. }
  65431. hue = ColorCurves.clamp(hue, 0, 360);
  65432. density = ColorCurves.clamp(density, -100, 100);
  65433. saturation = ColorCurves.clamp(saturation, -100, 100);
  65434. exposure = ColorCurves.clamp(exposure, -100, 100);
  65435. // Remap the slider/config filter density with non-linear mapping and also scale by half
  65436. // so that the maximum filter density is only 50% control. This provides fine control
  65437. // for small values and reasonable range.
  65438. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  65439. density *= 0.5;
  65440. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  65441. if (density < 0) {
  65442. density *= -1;
  65443. hue = (hue + 180) % 360;
  65444. }
  65445. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  65446. result.scaleToRef(2, result);
  65447. result.a = 1 + 0.01 * saturation;
  65448. };
  65449. /**
  65450. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  65451. * @param value The input slider value in range [-100,100].
  65452. * @returns Adjusted value.
  65453. */
  65454. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  65455. value /= 100;
  65456. var x = Math.abs(value);
  65457. x = Math.pow(x, 2);
  65458. if (value < 0) {
  65459. x *= -1;
  65460. }
  65461. x *= 100;
  65462. return x;
  65463. };
  65464. /**
  65465. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  65466. * @param hue The hue (H) input.
  65467. * @param saturation The saturation (S) input.
  65468. * @param brightness The brightness (B) input.
  65469. * @result An RGBA color represented as Vector4.
  65470. */
  65471. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  65472. var h = ColorCurves.clamp(hue, 0, 360);
  65473. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  65474. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  65475. if (s === 0) {
  65476. result.r = v;
  65477. result.g = v;
  65478. result.b = v;
  65479. }
  65480. else {
  65481. // sector 0 to 5
  65482. h /= 60;
  65483. var i = Math.floor(h);
  65484. // fractional part of h
  65485. var f = h - i;
  65486. var p = v * (1 - s);
  65487. var q = v * (1 - s * f);
  65488. var t = v * (1 - s * (1 - f));
  65489. switch (i) {
  65490. case 0:
  65491. result.r = v;
  65492. result.g = t;
  65493. result.b = p;
  65494. break;
  65495. case 1:
  65496. result.r = q;
  65497. result.g = v;
  65498. result.b = p;
  65499. break;
  65500. case 2:
  65501. result.r = p;
  65502. result.g = v;
  65503. result.b = t;
  65504. break;
  65505. case 3:
  65506. result.r = p;
  65507. result.g = q;
  65508. result.b = v;
  65509. break;
  65510. case 4:
  65511. result.r = t;
  65512. result.g = p;
  65513. result.b = v;
  65514. break;
  65515. default:// case 5:
  65516. result.r = v;
  65517. result.g = p;
  65518. result.b = q;
  65519. break;
  65520. }
  65521. }
  65522. result.a = 1;
  65523. };
  65524. /**
  65525. * Returns a value clamped between min and max
  65526. * @param value The value to clamp
  65527. * @param min The minimum of value
  65528. * @param max The maximum of value
  65529. * @returns The clamped value.
  65530. */
  65531. ColorCurves.clamp = function (value, min, max) {
  65532. return Math.min(Math.max(value, min), max);
  65533. };
  65534. /**
  65535. * Clones the current color curve instance.
  65536. * @return The cloned curves
  65537. */
  65538. ColorCurves.prototype.clone = function () {
  65539. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  65540. };
  65541. /**
  65542. * Serializes the current color curve instance to a json representation.
  65543. * @return a JSON representation
  65544. */
  65545. ColorCurves.prototype.serialize = function () {
  65546. return BABYLON.SerializationHelper.Serialize(this);
  65547. };
  65548. /**
  65549. * Parses the color curve from a json representation.
  65550. * @param source the JSON source to parse
  65551. * @return The parsed curves
  65552. */
  65553. ColorCurves.Parse = function (source) {
  65554. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  65555. };
  65556. __decorate([
  65557. BABYLON.serialize()
  65558. ], ColorCurves.prototype, "_globalHue", void 0);
  65559. __decorate([
  65560. BABYLON.serialize()
  65561. ], ColorCurves.prototype, "_globalDensity", void 0);
  65562. __decorate([
  65563. BABYLON.serialize()
  65564. ], ColorCurves.prototype, "_globalSaturation", void 0);
  65565. __decorate([
  65566. BABYLON.serialize()
  65567. ], ColorCurves.prototype, "_globalExposure", void 0);
  65568. __decorate([
  65569. BABYLON.serialize()
  65570. ], ColorCurves.prototype, "_highlightsHue", void 0);
  65571. __decorate([
  65572. BABYLON.serialize()
  65573. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  65574. __decorate([
  65575. BABYLON.serialize()
  65576. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  65577. __decorate([
  65578. BABYLON.serialize()
  65579. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  65580. __decorate([
  65581. BABYLON.serialize()
  65582. ], ColorCurves.prototype, "_midtonesHue", void 0);
  65583. __decorate([
  65584. BABYLON.serialize()
  65585. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  65586. __decorate([
  65587. BABYLON.serialize()
  65588. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  65589. __decorate([
  65590. BABYLON.serialize()
  65591. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  65592. return ColorCurves;
  65593. }());
  65594. BABYLON.ColorCurves = ColorCurves;
  65595. })(BABYLON || (BABYLON = {}));
  65596. //# sourceMappingURL=babylon.colorCurves.js.map
  65597. var BABYLON;
  65598. (function (BABYLON) {
  65599. var Octree = (function () {
  65600. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  65601. if (maxDepth === void 0) { maxDepth = 2; }
  65602. this.maxDepth = maxDepth;
  65603. this.dynamicContent = new Array();
  65604. this._maxBlockCapacity = maxBlockCapacity || 64;
  65605. this._selectionContent = new BABYLON.SmartArray(1024);
  65606. this._creationFunc = creationFunc;
  65607. }
  65608. // Methods
  65609. Octree.prototype.update = function (worldMin, worldMax, entries) {
  65610. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  65611. };
  65612. Octree.prototype.addMesh = function (entry) {
  65613. for (var index = 0; index < this.blocks.length; index++) {
  65614. var block = this.blocks[index];
  65615. block.addEntry(entry);
  65616. }
  65617. };
  65618. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  65619. this._selectionContent.reset();
  65620. for (var index = 0; index < this.blocks.length; index++) {
  65621. var block = this.blocks[index];
  65622. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  65623. }
  65624. if (allowDuplicate) {
  65625. this._selectionContent.concat(this.dynamicContent);
  65626. }
  65627. else {
  65628. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65629. }
  65630. return this._selectionContent;
  65631. };
  65632. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  65633. this._selectionContent.reset();
  65634. for (var index = 0; index < this.blocks.length; index++) {
  65635. var block = this.blocks[index];
  65636. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  65637. }
  65638. if (allowDuplicate) {
  65639. this._selectionContent.concat(this.dynamicContent);
  65640. }
  65641. else {
  65642. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65643. }
  65644. return this._selectionContent;
  65645. };
  65646. Octree.prototype.intersectsRay = function (ray) {
  65647. this._selectionContent.reset();
  65648. for (var index = 0; index < this.blocks.length; index++) {
  65649. var block = this.blocks[index];
  65650. block.intersectsRay(ray, this._selectionContent);
  65651. }
  65652. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65653. return this._selectionContent;
  65654. };
  65655. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  65656. target.blocks = new Array();
  65657. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  65658. // Segmenting space
  65659. for (var x = 0; x < 2; x++) {
  65660. for (var y = 0; y < 2; y++) {
  65661. for (var z = 0; z < 2; z++) {
  65662. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  65663. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  65664. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  65665. block.addEntries(entries);
  65666. target.blocks.push(block);
  65667. }
  65668. }
  65669. }
  65670. };
  65671. Octree.CreationFuncForMeshes = function (entry, block) {
  65672. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  65673. block.entries.push(entry);
  65674. }
  65675. };
  65676. Octree.CreationFuncForSubMeshes = function (entry, block) {
  65677. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  65678. block.entries.push(entry);
  65679. }
  65680. };
  65681. return Octree;
  65682. }());
  65683. BABYLON.Octree = Octree;
  65684. })(BABYLON || (BABYLON = {}));
  65685. //# sourceMappingURL=babylon.octree.js.map
  65686. var BABYLON;
  65687. (function (BABYLON) {
  65688. var OctreeBlock = (function () {
  65689. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  65690. this.entries = new Array();
  65691. this._boundingVectors = new Array();
  65692. this._capacity = capacity;
  65693. this._depth = depth;
  65694. this._maxDepth = maxDepth;
  65695. this._creationFunc = creationFunc;
  65696. this._minPoint = minPoint;
  65697. this._maxPoint = maxPoint;
  65698. this._boundingVectors.push(minPoint.clone());
  65699. this._boundingVectors.push(maxPoint.clone());
  65700. this._boundingVectors.push(minPoint.clone());
  65701. this._boundingVectors[2].x = maxPoint.x;
  65702. this._boundingVectors.push(minPoint.clone());
  65703. this._boundingVectors[3].y = maxPoint.y;
  65704. this._boundingVectors.push(minPoint.clone());
  65705. this._boundingVectors[4].z = maxPoint.z;
  65706. this._boundingVectors.push(maxPoint.clone());
  65707. this._boundingVectors[5].z = minPoint.z;
  65708. this._boundingVectors.push(maxPoint.clone());
  65709. this._boundingVectors[6].x = minPoint.x;
  65710. this._boundingVectors.push(maxPoint.clone());
  65711. this._boundingVectors[7].y = minPoint.y;
  65712. }
  65713. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  65714. // Property
  65715. get: function () {
  65716. return this._capacity;
  65717. },
  65718. enumerable: true,
  65719. configurable: true
  65720. });
  65721. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  65722. get: function () {
  65723. return this._minPoint;
  65724. },
  65725. enumerable: true,
  65726. configurable: true
  65727. });
  65728. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  65729. get: function () {
  65730. return this._maxPoint;
  65731. },
  65732. enumerable: true,
  65733. configurable: true
  65734. });
  65735. // Methods
  65736. OctreeBlock.prototype.addEntry = function (entry) {
  65737. if (this.blocks) {
  65738. for (var index = 0; index < this.blocks.length; index++) {
  65739. var block = this.blocks[index];
  65740. block.addEntry(entry);
  65741. }
  65742. return;
  65743. }
  65744. this._creationFunc(entry, this);
  65745. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  65746. this.createInnerBlocks();
  65747. }
  65748. };
  65749. OctreeBlock.prototype.addEntries = function (entries) {
  65750. for (var index = 0; index < entries.length; index++) {
  65751. var mesh = entries[index];
  65752. this.addEntry(mesh);
  65753. }
  65754. };
  65755. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  65756. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  65757. if (this.blocks) {
  65758. for (var index = 0; index < this.blocks.length; index++) {
  65759. var block = this.blocks[index];
  65760. block.select(frustumPlanes, selection, allowDuplicate);
  65761. }
  65762. return;
  65763. }
  65764. if (allowDuplicate) {
  65765. selection.concat(this.entries);
  65766. }
  65767. else {
  65768. selection.concatWithNoDuplicate(this.entries);
  65769. }
  65770. }
  65771. };
  65772. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  65773. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  65774. if (this.blocks) {
  65775. for (var index = 0; index < this.blocks.length; index++) {
  65776. var block = this.blocks[index];
  65777. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  65778. }
  65779. return;
  65780. }
  65781. if (allowDuplicate) {
  65782. selection.concat(this.entries);
  65783. }
  65784. else {
  65785. selection.concatWithNoDuplicate(this.entries);
  65786. }
  65787. }
  65788. };
  65789. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  65790. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  65791. if (this.blocks) {
  65792. for (var index = 0; index < this.blocks.length; index++) {
  65793. var block = this.blocks[index];
  65794. block.intersectsRay(ray, selection);
  65795. }
  65796. return;
  65797. }
  65798. selection.concatWithNoDuplicate(this.entries);
  65799. }
  65800. };
  65801. OctreeBlock.prototype.createInnerBlocks = function () {
  65802. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  65803. };
  65804. return OctreeBlock;
  65805. }());
  65806. BABYLON.OctreeBlock = OctreeBlock;
  65807. })(BABYLON || (BABYLON = {}));
  65808. //# sourceMappingURL=babylon.octreeBlock.js.map
  65809. var BABYLON;
  65810. (function (BABYLON) {
  65811. var SIMDVector3 = (function () {
  65812. function SIMDVector3() {
  65813. }
  65814. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  65815. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  65816. };
  65817. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  65818. var m = transformation.m;
  65819. var m0 = SIMD.Float32x4.load(m, 0);
  65820. var m1 = SIMD.Float32x4.load(m, 4);
  65821. var m2 = SIMD.Float32x4.load(m, 8);
  65822. var m3 = SIMD.Float32x4.load(m, 12);
  65823. 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));
  65824. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  65825. result.x = SIMD.Float32x4.extractLane(r, 0);
  65826. result.y = SIMD.Float32x4.extractLane(r, 1);
  65827. result.z = SIMD.Float32x4.extractLane(r, 2);
  65828. };
  65829. return SIMDVector3;
  65830. }());
  65831. var SIMDMatrix = (function () {
  65832. function SIMDMatrix() {
  65833. }
  65834. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  65835. var tm = this.m;
  65836. var om = other.m;
  65837. var m0 = SIMD.Float32x4.load(om, 0);
  65838. var m1 = SIMD.Float32x4.load(om, 4);
  65839. var m2 = SIMD.Float32x4.load(om, 8);
  65840. var m3 = SIMD.Float32x4.load(om, 12);
  65841. for (var i = 0; i < 16; i += 4) {
  65842. 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)))));
  65843. }
  65844. return this;
  65845. };
  65846. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  65847. var src = this.m;
  65848. var dest = other.m;
  65849. // Load the 4 rows
  65850. var src0 = SIMD.Float32x4.load(src, 0);
  65851. var src1 = SIMD.Float32x4.load(src, 4);
  65852. var src2 = SIMD.Float32x4.load(src, 8);
  65853. var src3 = SIMD.Float32x4.load(src, 12);
  65854. // Transpose the source matrix. Sort of. Not a true transpose operation
  65855. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  65856. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  65857. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  65858. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  65859. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  65860. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  65861. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  65862. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  65863. // This is a true transposition, but it will lead to an incorrect result
  65864. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  65865. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  65866. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  65867. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  65868. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  65869. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  65870. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  65871. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  65872. // ----
  65873. tmp1 = SIMD.Float32x4.mul(row2, row3);
  65874. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65875. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  65876. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  65877. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65878. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  65879. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  65880. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  65881. // ----
  65882. tmp1 = SIMD.Float32x4.mul(row1, row2);
  65883. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65884. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  65885. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  65886. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65887. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  65888. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  65889. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  65890. // ----
  65891. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  65892. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65893. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  65894. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  65895. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  65896. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65897. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  65898. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  65899. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  65900. // ----
  65901. tmp1 = SIMD.Float32x4.mul(row0, row1);
  65902. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65903. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  65904. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  65905. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65906. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  65907. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  65908. // ----
  65909. tmp1 = SIMD.Float32x4.mul(row0, row3);
  65910. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65911. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  65912. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  65913. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65914. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  65915. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  65916. // ----
  65917. tmp1 = SIMD.Float32x4.mul(row0, row2);
  65918. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65919. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  65920. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  65921. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65922. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  65923. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  65924. // Compute determinant
  65925. var det = SIMD.Float32x4.mul(row0, minor0);
  65926. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  65927. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  65928. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  65929. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  65930. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  65931. // These shuffles aren't necessary if the faulty transposition is done
  65932. // up at the top of this function.
  65933. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  65934. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  65935. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  65936. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  65937. // Compute final values by multiplying with 1/det
  65938. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  65939. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  65940. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  65941. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  65942. return this;
  65943. };
  65944. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  65945. var out = result.m;
  65946. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  65947. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  65948. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  65949. // cc.kmVec3Subtract(f, pCenter, pEye);
  65950. var f = SIMD.Float32x4.sub(center, eye);
  65951. // cc.kmVec3Normalize(f, f);
  65952. var tmp = SIMD.Float32x4.mul(f, f);
  65953. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65954. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65955. // cc.kmVec3Assign(up, pUp);
  65956. // cc.kmVec3Normalize(up, up);
  65957. tmp = SIMD.Float32x4.mul(up, up);
  65958. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65959. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65960. // cc.kmVec3Cross(s, f, up);
  65961. 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)));
  65962. // cc.kmVec3Normalize(s, s);
  65963. tmp = SIMD.Float32x4.mul(s, s);
  65964. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65965. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65966. // cc.kmVec3Cross(u, s, f);
  65967. 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)));
  65968. // cc.kmVec3Normalize(s, s);
  65969. tmp = SIMD.Float32x4.mul(s, s);
  65970. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65971. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65972. var zero = SIMD.Float32x4.splat(0.0);
  65973. s = SIMD.Float32x4.neg(s);
  65974. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  65975. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  65976. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  65977. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  65978. 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);
  65979. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  65980. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  65981. 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)))));
  65982. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  65983. 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)))));
  65984. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  65985. 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)))));
  65986. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  65987. 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)))));
  65988. };
  65989. return SIMDMatrix;
  65990. }());
  65991. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  65992. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  65993. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  65994. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  65995. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  65996. var SIMDHelper = (function () {
  65997. function SIMDHelper() {
  65998. }
  65999. Object.defineProperty(SIMDHelper, "IsEnabled", {
  66000. get: function () {
  66001. return SIMDHelper._isEnabled;
  66002. },
  66003. enumerable: true,
  66004. configurable: true
  66005. });
  66006. SIMDHelper.DisableSIMD = function () {
  66007. // Replace functions
  66008. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  66009. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  66010. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  66011. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  66012. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  66013. SIMDHelper._isEnabled = false;
  66014. };
  66015. SIMDHelper.EnableSIMD = function () {
  66016. if (self.SIMD === undefined) {
  66017. return;
  66018. }
  66019. // check if polyfills needed
  66020. if (!self.Math.fround) {
  66021. self.Math.fround = (function (array) { return function (x) {
  66022. return array[0] = x, array[0];
  66023. }; })(new Float32Array(1));
  66024. }
  66025. if (!self.Math.imul) {
  66026. self.Math.imul = function (a, b) {
  66027. var ah = (a >>> 16) & 0xffff;
  66028. var al = a & 0xffff;
  66029. var bh = (b >>> 16) & 0xffff;
  66030. var bl = b & 0xffff;
  66031. // the shift by 0 fixes the sign on the high part
  66032. // the final |0 converts the unsigned value into a signed value
  66033. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  66034. };
  66035. }
  66036. // Replace functions
  66037. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  66038. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  66039. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  66040. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  66041. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  66042. SIMDHelper._isEnabled = true;
  66043. };
  66044. SIMDHelper._isEnabled = false;
  66045. return SIMDHelper;
  66046. }());
  66047. BABYLON.SIMDHelper = SIMDHelper;
  66048. })(BABYLON || (BABYLON = {}));
  66049. //# sourceMappingURL=babylon.math.SIMD.js.map
  66050. var BABYLON;
  66051. (function (BABYLON) {
  66052. var VRDistortionCorrectionPostProcess = (function (_super) {
  66053. __extends(VRDistortionCorrectionPostProcess, _super);
  66054. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  66055. var _this = _super.call(this, name, "vrDistortionCorrection", [
  66056. 'LensCenter',
  66057. 'Scale',
  66058. 'ScaleIn',
  66059. 'HmdWarpParam'
  66060. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  66061. _this._isRightEye = isRightEye;
  66062. _this._distortionFactors = vrMetrics.distortionK;
  66063. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  66064. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  66065. _this.adaptScaleToCurrentViewport = true;
  66066. _this.onSizeChangedObservable.add(function () {
  66067. _this.aspectRatio = _this.width * .5 / _this.height;
  66068. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  66069. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  66070. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  66071. });
  66072. _this.onApplyObservable.add(function (effect) {
  66073. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  66074. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  66075. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  66076. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  66077. });
  66078. return _this;
  66079. }
  66080. return VRDistortionCorrectionPostProcess;
  66081. }(BABYLON.PostProcess));
  66082. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  66083. })(BABYLON || (BABYLON = {}));
  66084. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  66085. var BABYLON;
  66086. (function (BABYLON) {
  66087. var AnaglyphPostProcess = (function (_super) {
  66088. __extends(AnaglyphPostProcess, _super);
  66089. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  66090. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  66091. _this._passedProcess = rigCameras[0]._rigPostProcess;
  66092. _this.onApplyObservable.add(function (effect) {
  66093. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  66094. });
  66095. return _this;
  66096. }
  66097. return AnaglyphPostProcess;
  66098. }(BABYLON.PostProcess));
  66099. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  66100. })(BABYLON || (BABYLON = {}));
  66101. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  66102. var BABYLON;
  66103. (function (BABYLON) {
  66104. var StereoscopicInterlacePostProcess = (function (_super) {
  66105. __extends(StereoscopicInterlacePostProcess, _super);
  66106. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  66107. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  66108. _this._passedProcess = rigCameras[0]._rigPostProcess;
  66109. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  66110. _this.onSizeChangedObservable.add(function () {
  66111. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  66112. });
  66113. _this.onApplyObservable.add(function (effect) {
  66114. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  66115. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  66116. });
  66117. return _this;
  66118. }
  66119. return StereoscopicInterlacePostProcess;
  66120. }(BABYLON.PostProcess));
  66121. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  66122. })(BABYLON || (BABYLON = {}));
  66123. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  66124. var BABYLON;
  66125. (function (BABYLON) {
  66126. var FreeCameraDeviceOrientationInput = (function () {
  66127. function FreeCameraDeviceOrientationInput() {
  66128. var _this = this;
  66129. this._screenOrientationAngle = 0;
  66130. this._screenQuaternion = new BABYLON.Quaternion();
  66131. this._alpha = 0;
  66132. this._beta = 0;
  66133. this._gamma = 0;
  66134. this._orientationChanged = function () {
  66135. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  66136. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  66137. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  66138. };
  66139. this._deviceOrientation = function (evt) {
  66140. _this._alpha = evt.alpha;
  66141. _this._beta = evt.beta;
  66142. _this._gamma = evt.gamma;
  66143. };
  66144. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  66145. this._orientationChanged();
  66146. }
  66147. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  66148. get: function () {
  66149. return this._camera;
  66150. },
  66151. set: function (camera) {
  66152. this._camera = camera;
  66153. if (this._camera != null && !this._camera.rotationQuaternion) {
  66154. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  66155. }
  66156. },
  66157. enumerable: true,
  66158. configurable: true
  66159. });
  66160. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  66161. window.addEventListener("orientationchange", this._orientationChanged);
  66162. window.addEventListener("deviceorientation", this._deviceOrientation);
  66163. //In certain cases, the attach control is called AFTER orientation was changed,
  66164. //So this is needed.
  66165. this._orientationChanged();
  66166. };
  66167. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  66168. window.removeEventListener("orientationchange", this._orientationChanged);
  66169. window.removeEventListener("deviceorientation", this._deviceOrientation);
  66170. };
  66171. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  66172. //if no device orientation provided, don't update the rotation.
  66173. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  66174. if (!this._alpha)
  66175. return;
  66176. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  66177. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  66178. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  66179. //Mirror on XY Plane
  66180. this._camera.rotationQuaternion.z *= -1;
  66181. this._camera.rotationQuaternion.w *= -1;
  66182. };
  66183. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  66184. return "FreeCameraDeviceOrientationInput";
  66185. };
  66186. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  66187. return "deviceOrientation";
  66188. };
  66189. return FreeCameraDeviceOrientationInput;
  66190. }());
  66191. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  66192. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  66193. })(BABYLON || (BABYLON = {}));
  66194. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  66195. var BABYLON;
  66196. (function (BABYLON) {
  66197. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  66198. function ArcRotateCameraVRDeviceOrientationInput() {
  66199. this.alphaCorrection = 1;
  66200. this.betaCorrection = 1;
  66201. this.gammaCorrection = 1;
  66202. this._alpha = 0;
  66203. this._beta = 0;
  66204. this._gamma = 0;
  66205. this._dirty = false;
  66206. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  66207. }
  66208. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  66209. this.camera.attachControl(element, noPreventDefault);
  66210. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  66211. };
  66212. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  66213. var camera = this.camera;
  66214. this._alpha = +evt.alpha | 0;
  66215. this._beta = +evt.beta | 0;
  66216. this._gamma = +evt.gamma | 0;
  66217. this._dirty = true;
  66218. };
  66219. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  66220. if (this._dirty) {
  66221. this._dirty = false;
  66222. if (this._gamma < 0) {
  66223. this._gamma = 180 + this._gamma;
  66224. }
  66225. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  66226. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  66227. }
  66228. };
  66229. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  66230. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  66231. };
  66232. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  66233. return "ArcRotateCameraVRDeviceOrientationInput";
  66234. };
  66235. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  66236. return "VRDeviceOrientation";
  66237. };
  66238. return ArcRotateCameraVRDeviceOrientationInput;
  66239. }());
  66240. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  66241. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  66242. })(BABYLON || (BABYLON = {}));
  66243. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  66244. var BABYLON;
  66245. (function (BABYLON) {
  66246. var VRCameraMetrics = (function () {
  66247. function VRCameraMetrics() {
  66248. this.compensateDistortion = true;
  66249. }
  66250. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  66251. get: function () {
  66252. return this.hResolution / (2 * this.vResolution);
  66253. },
  66254. enumerable: true,
  66255. configurable: true
  66256. });
  66257. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  66258. get: function () {
  66259. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  66260. },
  66261. enumerable: true,
  66262. configurable: true
  66263. });
  66264. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  66265. get: function () {
  66266. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  66267. var h = (4 * meters) / this.hScreenSize;
  66268. return BABYLON.Matrix.Translation(h, 0, 0);
  66269. },
  66270. enumerable: true,
  66271. configurable: true
  66272. });
  66273. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  66274. get: function () {
  66275. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  66276. var h = (4 * meters) / this.hScreenSize;
  66277. return BABYLON.Matrix.Translation(-h, 0, 0);
  66278. },
  66279. enumerable: true,
  66280. configurable: true
  66281. });
  66282. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  66283. get: function () {
  66284. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  66285. },
  66286. enumerable: true,
  66287. configurable: true
  66288. });
  66289. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  66290. get: function () {
  66291. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  66292. },
  66293. enumerable: true,
  66294. configurable: true
  66295. });
  66296. VRCameraMetrics.GetDefault = function () {
  66297. var result = new VRCameraMetrics();
  66298. result.hResolution = 1280;
  66299. result.vResolution = 800;
  66300. result.hScreenSize = 0.149759993;
  66301. result.vScreenSize = 0.0935999975;
  66302. result.vScreenCenter = 0.0467999987;
  66303. result.eyeToScreenDistance = 0.0410000011;
  66304. result.lensSeparationDistance = 0.0635000020;
  66305. result.interpupillaryDistance = 0.0640000030;
  66306. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  66307. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  66308. result.postProcessScaleFactor = 1.714605507808412;
  66309. result.lensCenterOffset = 0.151976421;
  66310. return result;
  66311. };
  66312. return VRCameraMetrics;
  66313. }());
  66314. BABYLON.VRCameraMetrics = VRCameraMetrics;
  66315. })(BABYLON || (BABYLON = {}));
  66316. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  66317. var BABYLON;
  66318. (function (BABYLON) {
  66319. var WebVRFreeCamera = (function (_super) {
  66320. __extends(WebVRFreeCamera, _super);
  66321. function WebVRFreeCamera(name, position, scene, webVROptions) {
  66322. if (webVROptions === void 0) { webVROptions = {}; }
  66323. var _this = _super.call(this, name, position, scene) || this;
  66324. _this.webVROptions = webVROptions;
  66325. _this._vrDevice = null;
  66326. _this.rawPose = null;
  66327. _this._vrEnabled = false;
  66328. _this._specsVersion = 1.1;
  66329. _this._attached = false;
  66330. _this._positionOffset = BABYLON.Vector3.Zero();
  66331. _this._descendants = [];
  66332. _this.devicePosition = BABYLON.Vector3.Zero();
  66333. _this.deviceScaleFactor = 1;
  66334. _this.controllers = [];
  66335. _this.onControllersAttachedObservable = new BABYLON.Observable();
  66336. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  66337. _this.minZ = 0.1;
  66338. //legacy support - the compensation boolean was removed.
  66339. if (arguments.length === 5) {
  66340. _this.webVROptions = arguments[4];
  66341. }
  66342. // default webVR options
  66343. if (_this.webVROptions.trackPosition == undefined) {
  66344. _this.webVROptions.trackPosition = true;
  66345. }
  66346. if (_this.webVROptions.controllerMeshes == undefined) {
  66347. _this.webVROptions.controllerMeshes = true;
  66348. }
  66349. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  66350. _this.webVROptions.defaultLightingOnControllers = true;
  66351. }
  66352. _this.rotationQuaternion = new BABYLON.Quaternion();
  66353. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66354. if (_this.webVROptions && _this.webVROptions.positionScale) {
  66355. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  66356. }
  66357. //enable VR
  66358. _this.getEngine().initWebVR();
  66359. //check specs version
  66360. if (!window.VRFrameData) {
  66361. _this._specsVersion = 1.0;
  66362. _this._frameData = {};
  66363. }
  66364. else {
  66365. _this._frameData = new VRFrameData();
  66366. }
  66367. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  66368. if (!device) {
  66369. return;
  66370. }
  66371. _this._vrEnabled = true;
  66372. _this._vrDevice = device;
  66373. //reset the rig parameters.
  66374. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  66375. if (_this._attached) {
  66376. _this.getEngine().enableVR(_this._vrDevice);
  66377. }
  66378. });
  66379. /**
  66380. * The idea behind the following lines:
  66381. * objects that have the camera as parent should actually have the rig cameras as a parent.
  66382. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  66383. * the second will not show it correctly.
  66384. *
  66385. * To solve this - each object that has the camera as parent will be added to a protected array.
  66386. * When the rig camera renders, it will take this array and set all of those to be its children.
  66387. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  66388. * Amazing!
  66389. */
  66390. scene.onBeforeCameraRenderObservable.add(function (camera) {
  66391. if (camera.parent === _this && _this.rigParenting) {
  66392. _this._descendants = _this.getDescendants(true, function (n) {
  66393. // don't take the cameras or the controllers!
  66394. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  66395. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  66396. return !isController && !isRigCamera;
  66397. });
  66398. _this._descendants.forEach(function (node) {
  66399. node.parent = camera;
  66400. });
  66401. }
  66402. });
  66403. scene.onAfterCameraRenderObservable.add(function (camera) {
  66404. if (camera.parent === _this && _this.rigParenting) {
  66405. _this._descendants.forEach(function (node) {
  66406. node.parent = _this;
  66407. });
  66408. }
  66409. });
  66410. return _this;
  66411. }
  66412. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  66413. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  66414. var gp = _a[_i];
  66415. if (gp.hand === name) {
  66416. return gp;
  66417. }
  66418. }
  66419. return undefined;
  66420. };
  66421. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  66422. get: function () {
  66423. if (!this._leftController) {
  66424. this._leftController = this.getControllerByName("left");
  66425. }
  66426. return this._leftController;
  66427. },
  66428. enumerable: true,
  66429. configurable: true
  66430. });
  66431. ;
  66432. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  66433. get: function () {
  66434. if (!this._rightController) {
  66435. this._rightController = this.getControllerByName("right");
  66436. }
  66437. return this._rightController;
  66438. },
  66439. enumerable: true,
  66440. configurable: true
  66441. });
  66442. ;
  66443. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  66444. if (length === void 0) { length = 100; }
  66445. if (this.leftCamera) {
  66446. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  66447. }
  66448. else {
  66449. return _super.prototype.getForwardRay.call(this, length);
  66450. }
  66451. };
  66452. WebVRFreeCamera.prototype._checkInputs = function () {
  66453. if (this._vrEnabled) {
  66454. if (this._specsVersion === 1.1) {
  66455. this._vrDevice.getFrameData(this._frameData);
  66456. }
  66457. else {
  66458. //backwards comp
  66459. var pose = this._vrDevice.getPose();
  66460. this._frameData.pose = pose;
  66461. }
  66462. this.updateFromDevice(this._frameData.pose);
  66463. }
  66464. _super.prototype._checkInputs.call(this);
  66465. };
  66466. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  66467. if (poseData && poseData.orientation) {
  66468. this.rawPose = poseData;
  66469. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  66470. if (this.getScene().useRightHandedSystem) {
  66471. this.deviceRotationQuaternion.z *= -1;
  66472. this.deviceRotationQuaternion.w *= -1;
  66473. }
  66474. if (this.webVROptions.trackPosition && this.rawPose.position) {
  66475. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  66476. if (this.getScene().useRightHandedSystem) {
  66477. this.devicePosition.z *= -1;
  66478. }
  66479. }
  66480. }
  66481. };
  66482. /**
  66483. * WebVR's attach control will start broadcasting frames to the device.
  66484. * Note that in certain browsers (chrome for example) this function must be called
  66485. * within a user-interaction callback. Example:
  66486. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  66487. *
  66488. * @param {HTMLElement} element
  66489. * @param {boolean} [noPreventDefault]
  66490. *
  66491. * @memberOf WebVRFreeCamera
  66492. */
  66493. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  66494. _super.prototype.attachControl.call(this, element, noPreventDefault);
  66495. this._attached = true;
  66496. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  66497. if (this._vrEnabled) {
  66498. this.getEngine().enableVR(this._vrDevice);
  66499. }
  66500. // try to attach the controllers, if found.
  66501. this.initControllers();
  66502. };
  66503. WebVRFreeCamera.prototype.detachControl = function (element) {
  66504. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  66505. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  66506. _super.prototype.detachControl.call(this, element);
  66507. this._vrEnabled = false;
  66508. this._attached = false;
  66509. this.getEngine().disableVR();
  66510. };
  66511. WebVRFreeCamera.prototype.getClassName = function () {
  66512. return "WebVRFreeCamera";
  66513. };
  66514. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  66515. //uses the vrDisplay's "resetPose()".
  66516. //pitch and roll won't be affected.
  66517. this._vrDevice.resetPose();
  66518. };
  66519. WebVRFreeCamera.prototype._updateRigCameras = function () {
  66520. var camLeft = this._rigCameras[0];
  66521. var camRight = this._rigCameras[1];
  66522. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66523. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66524. camLeft.position.copyFrom(this.devicePosition);
  66525. camRight.position.copyFrom(this.devicePosition);
  66526. };
  66527. /**
  66528. * This function is called by the two RIG cameras.
  66529. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  66530. */
  66531. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  66532. var _this = this;
  66533. //WebVR 1.0
  66534. if (this._cameraRigParams["specs"] === 1.0) {
  66535. this._updateCameraRotationMatrix();
  66536. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  66537. // Computing target and final matrix
  66538. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  66539. if (this.getScene().useRightHandedSystem) {
  66540. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  66541. }
  66542. else {
  66543. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  66544. }
  66545. //now move the eye in the right direction
  66546. var eyeParams = this._cameraRigParams["eyeParameters"];
  66547. var offset = eyeParams.offset;
  66548. // it will actually always be 0, but just in case
  66549. if (this.getScene().useRightHandedSystem) {
  66550. offset[2] *= -1;
  66551. }
  66552. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  66553. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  66554. }
  66555. else {
  66556. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  66557. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  66558. if (!this.getScene().useRightHandedSystem) {
  66559. [2, 6, 8, 9, 14].forEach(function (num) {
  66560. _this._webvrViewMatrix.m[num] *= -1;
  66561. });
  66562. }
  66563. // update the camera rotation matrix
  66564. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  66565. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  66566. // Computing target and final matrix
  66567. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  66568. }
  66569. var parentCamera = this._cameraRigParams["parentCamera"];
  66570. // should the view matrix be updated with scale and position offset?
  66571. if (parentCamera.deviceScaleFactor !== 1) {
  66572. this._webvrViewMatrix.invert();
  66573. // scale the position, if set
  66574. if (parentCamera.deviceScaleFactor) {
  66575. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  66576. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  66577. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  66578. }
  66579. this._webvrViewMatrix.invert();
  66580. }
  66581. return this._webvrViewMatrix;
  66582. };
  66583. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  66584. var _this = this;
  66585. if (this._cameraRigParams["specs"] === 1.0) {
  66586. var eyeParams = this._cameraRigParams["eyeParameters"];
  66587. // deprecated!!
  66588. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, this.minZ, this.maxZ, this._projectionMatrix, this.getScene().useRightHandedSystem);
  66589. }
  66590. else {
  66591. var parentCamera = this.parent;
  66592. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  66593. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  66594. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  66595. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  66596. //babylon compatible matrix
  66597. if (!this.getScene().useRightHandedSystem) {
  66598. [8, 9, 10, 11].forEach(function (num) {
  66599. _this._projectionMatrix.m[num] *= -1;
  66600. });
  66601. }
  66602. }
  66603. return this._projectionMatrix;
  66604. };
  66605. WebVRFreeCamera.prototype.initControllers = function () {
  66606. var _this = this;
  66607. this.controllers = [];
  66608. var manager = this.getScene().gamepadManager;
  66609. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  66610. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  66611. var webVrController = gamepad;
  66612. if (webVrController.defaultModel) {
  66613. webVrController.defaultModel.setEnabled(false);
  66614. }
  66615. }
  66616. });
  66617. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  66618. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  66619. var webVrController = gamepad;
  66620. if (_this.webVROptions.controllerMeshes) {
  66621. if (webVrController.defaultModel) {
  66622. webVrController.defaultModel.setEnabled(true);
  66623. }
  66624. else {
  66625. // Load the meshes
  66626. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  66627. if (_this.webVROptions.defaultLightingOnControllers) {
  66628. if (!_this._lightOnControllers) {
  66629. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  66630. }
  66631. var activateLightOnSubMeshes_1 = function (mesh, light) {
  66632. var children = mesh.getChildren();
  66633. if (children.length !== 0) {
  66634. children.forEach(function (mesh) {
  66635. light.includedOnlyMeshes.push(mesh);
  66636. activateLightOnSubMeshes_1(mesh, light);
  66637. });
  66638. }
  66639. };
  66640. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  66641. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  66642. }
  66643. });
  66644. }
  66645. }
  66646. webVrController.attachToPoseControlledCamera(_this);
  66647. // since this is async - sanity check. Is the controller already stored?
  66648. if (_this.controllers.indexOf(webVrController) === -1) {
  66649. //add to the controllers array
  66650. _this.controllers.push(webVrController);
  66651. //did we find enough controllers? Great! let the developer know.
  66652. if (_this.controllers.length >= 2) {
  66653. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  66654. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  66655. // So we're overriding setting left & right manually to be sure
  66656. var firstViveWandDetected = false;
  66657. for (var i = 0; i < _this.controllers.length; i++) {
  66658. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  66659. if (!firstViveWandDetected) {
  66660. firstViveWandDetected = true;
  66661. _this.controllers[i].hand = "left";
  66662. }
  66663. else {
  66664. _this.controllers[i].hand = "right";
  66665. }
  66666. }
  66667. }
  66668. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  66669. }
  66670. }
  66671. }
  66672. });
  66673. };
  66674. return WebVRFreeCamera;
  66675. }(BABYLON.FreeCamera));
  66676. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  66677. })(BABYLON || (BABYLON = {}));
  66678. //# sourceMappingURL=babylon.webVRCamera.js.map
  66679. /// <reference path="babylon.freeCamera.ts" />
  66680. var BABYLON;
  66681. (function (BABYLON) {
  66682. // We're mainly based on the logic defined into the FreeCamera code
  66683. var DeviceOrientationCamera = (function (_super) {
  66684. __extends(DeviceOrientationCamera, _super);
  66685. function DeviceOrientationCamera(name, position, scene) {
  66686. var _this = _super.call(this, name, position, scene) || this;
  66687. _this._quaternionCache = new BABYLON.Quaternion();
  66688. _this.inputs.addDeviceOrientation();
  66689. return _this;
  66690. }
  66691. DeviceOrientationCamera.prototype.getClassName = function () {
  66692. return "DeviceOrientationCamera";
  66693. };
  66694. DeviceOrientationCamera.prototype._checkInputs = function () {
  66695. _super.prototype._checkInputs.call(this);
  66696. this._quaternionCache.copyFrom(this.rotationQuaternion);
  66697. if (this._initialQuaternion) {
  66698. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  66699. }
  66700. };
  66701. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  66702. var _this = this;
  66703. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  66704. //can only work if this camera has a rotation quaternion already.
  66705. if (!this.rotationQuaternion)
  66706. return;
  66707. if (!this._initialQuaternion) {
  66708. this._initialQuaternion = new BABYLON.Quaternion();
  66709. }
  66710. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  66711. ['x', 'y', 'z'].forEach(function (axisName) {
  66712. if (!axis[axisName]) {
  66713. _this._initialQuaternion[axisName] = 0;
  66714. }
  66715. else {
  66716. _this._initialQuaternion[axisName] *= -1;
  66717. }
  66718. });
  66719. this._initialQuaternion.normalize();
  66720. //force rotation update
  66721. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  66722. };
  66723. return DeviceOrientationCamera;
  66724. }(BABYLON.FreeCamera));
  66725. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  66726. })(BABYLON || (BABYLON = {}));
  66727. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  66728. var BABYLON;
  66729. (function (BABYLON) {
  66730. var VRDeviceOrientationFreeCamera = (function (_super) {
  66731. __extends(VRDeviceOrientationFreeCamera, _super);
  66732. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  66733. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66734. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66735. var _this = _super.call(this, name, position, scene) || this;
  66736. vrCameraMetrics.compensateDistortion = compensateDistortion;
  66737. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  66738. return _this;
  66739. }
  66740. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  66741. return "VRDeviceOrientationFreeCamera";
  66742. };
  66743. return VRDeviceOrientationFreeCamera;
  66744. }(BABYLON.DeviceOrientationCamera));
  66745. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  66746. var VRDeviceOrientationGamepadCamera = (function (_super) {
  66747. __extends(VRDeviceOrientationGamepadCamera, _super);
  66748. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  66749. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66750. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66751. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  66752. _this.inputs.addGamepad();
  66753. return _this;
  66754. }
  66755. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  66756. return "VRDeviceOrientationGamepadCamera";
  66757. };
  66758. return VRDeviceOrientationGamepadCamera;
  66759. }(VRDeviceOrientationFreeCamera));
  66760. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  66761. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  66762. __extends(VRDeviceOrientationArcRotateCamera, _super);
  66763. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  66764. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66765. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66766. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66767. vrCameraMetrics.compensateDistortion = compensateDistortion;
  66768. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  66769. _this.inputs.addVRDeviceOrientation();
  66770. return _this;
  66771. }
  66772. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  66773. return "VRDeviceOrientationArcRotateCamera";
  66774. };
  66775. return VRDeviceOrientationArcRotateCamera;
  66776. }(BABYLON.ArcRotateCamera));
  66777. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  66778. })(BABYLON || (BABYLON = {}));
  66779. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  66780. /// <reference path="babylon.freeCamera.ts" />
  66781. /// <reference path="babylon.arcRotateCamera.ts" />
  66782. /// <reference path="babylon.gamepadCamera.ts" />
  66783. /// <reference path="babylon.universalCamera.ts" />
  66784. var BABYLON;
  66785. (function (BABYLON) {
  66786. var AnaglyphFreeCamera = (function (_super) {
  66787. __extends(AnaglyphFreeCamera, _super);
  66788. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  66789. var _this = _super.call(this, name, position, scene) || this;
  66790. _this.interaxialDistance = interaxialDistance;
  66791. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66792. return _this;
  66793. }
  66794. AnaglyphFreeCamera.prototype.getClassName = function () {
  66795. return "AnaglyphFreeCamera";
  66796. };
  66797. return AnaglyphFreeCamera;
  66798. }(BABYLON.FreeCamera));
  66799. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  66800. var AnaglyphArcRotateCamera = (function (_super) {
  66801. __extends(AnaglyphArcRotateCamera, _super);
  66802. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  66803. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66804. _this.interaxialDistance = interaxialDistance;
  66805. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66806. return _this;
  66807. }
  66808. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  66809. return "AnaglyphArcRotateCamera";
  66810. };
  66811. return AnaglyphArcRotateCamera;
  66812. }(BABYLON.ArcRotateCamera));
  66813. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  66814. var AnaglyphGamepadCamera = (function (_super) {
  66815. __extends(AnaglyphGamepadCamera, _super);
  66816. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  66817. var _this = _super.call(this, name, position, scene) || this;
  66818. _this.interaxialDistance = interaxialDistance;
  66819. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66820. return _this;
  66821. }
  66822. AnaglyphGamepadCamera.prototype.getClassName = function () {
  66823. return "AnaglyphGamepadCamera";
  66824. };
  66825. return AnaglyphGamepadCamera;
  66826. }(BABYLON.GamepadCamera));
  66827. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  66828. var AnaglyphUniversalCamera = (function (_super) {
  66829. __extends(AnaglyphUniversalCamera, _super);
  66830. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  66831. var _this = _super.call(this, name, position, scene) || this;
  66832. _this.interaxialDistance = interaxialDistance;
  66833. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66834. return _this;
  66835. }
  66836. AnaglyphUniversalCamera.prototype.getClassName = function () {
  66837. return "AnaglyphUniversalCamera";
  66838. };
  66839. return AnaglyphUniversalCamera;
  66840. }(BABYLON.UniversalCamera));
  66841. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  66842. var StereoscopicFreeCamera = (function (_super) {
  66843. __extends(StereoscopicFreeCamera, _super);
  66844. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66845. var _this = _super.call(this, name, position, scene) || this;
  66846. _this.interaxialDistance = interaxialDistance;
  66847. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66848. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66849. return _this;
  66850. }
  66851. StereoscopicFreeCamera.prototype.getClassName = function () {
  66852. return "StereoscopicFreeCamera";
  66853. };
  66854. return StereoscopicFreeCamera;
  66855. }(BABYLON.FreeCamera));
  66856. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  66857. var StereoscopicArcRotateCamera = (function (_super) {
  66858. __extends(StereoscopicArcRotateCamera, _super);
  66859. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  66860. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66861. _this.interaxialDistance = interaxialDistance;
  66862. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66863. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66864. return _this;
  66865. }
  66866. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  66867. return "StereoscopicArcRotateCamera";
  66868. };
  66869. return StereoscopicArcRotateCamera;
  66870. }(BABYLON.ArcRotateCamera));
  66871. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  66872. var StereoscopicGamepadCamera = (function (_super) {
  66873. __extends(StereoscopicGamepadCamera, _super);
  66874. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66875. var _this = _super.call(this, name, position, scene) || this;
  66876. _this.interaxialDistance = interaxialDistance;
  66877. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66878. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66879. return _this;
  66880. }
  66881. StereoscopicGamepadCamera.prototype.getClassName = function () {
  66882. return "StereoscopicGamepadCamera";
  66883. };
  66884. return StereoscopicGamepadCamera;
  66885. }(BABYLON.GamepadCamera));
  66886. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  66887. var StereoscopicUniversalCamera = (function (_super) {
  66888. __extends(StereoscopicUniversalCamera, _super);
  66889. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66890. var _this = _super.call(this, name, position, scene) || this;
  66891. _this.interaxialDistance = interaxialDistance;
  66892. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66893. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66894. return _this;
  66895. }
  66896. StereoscopicUniversalCamera.prototype.getClassName = function () {
  66897. return "StereoscopicUniversalCamera";
  66898. };
  66899. return StereoscopicUniversalCamera;
  66900. }(BABYLON.UniversalCamera));
  66901. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  66902. })(BABYLON || (BABYLON = {}));
  66903. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  66904. var BABYLON;
  66905. (function (BABYLON) {
  66906. var VRExperienceHelper = (function () {
  66907. function VRExperienceHelper(scene, webVROptions) {
  66908. if (webVROptions === void 0) { webVROptions = {}; }
  66909. var _this = this;
  66910. this.webVROptions = webVROptions;
  66911. this._webVRsupportedAndReady = false;
  66912. this._isInVRMode = false;
  66913. this._scene = scene;
  66914. if (!this._scene.activeCamera) {
  66915. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  66916. }
  66917. else {
  66918. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  66919. if (scene.activeCamera.rotation) {
  66920. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  66921. }
  66922. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  66923. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  66924. }
  66925. this._scene.activeCamera = this._deviceOrientationCamera;
  66926. this._position = this._scene.activeCamera.position;
  66927. this._canvas = scene.getEngine().getRenderingCanvas();
  66928. this._scene.activeCamera.attachControl(this._canvas);
  66929. this._btnVR = document.createElement("BUTTON");
  66930. this._btnVR.className = "babylonVRicon";
  66931. this._btnVR.id = "babylonVRiconbtn";
  66932. this._btnVR.title = "Click to switch to VR";
  66933. 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) }";
  66934. var style = document.createElement('style');
  66935. style.appendChild(document.createTextNode(css));
  66936. document.getElementsByTagName('head')[0].appendChild(style);
  66937. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  66938. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  66939. window.addEventListener("resize", function () {
  66940. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  66941. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  66942. });
  66943. // Exiting VR mode using 'ESC' key on desktop
  66944. document.addEventListener("keydown", function (event) {
  66945. if (event.keyCode === 27 && _this._isInVRMode) {
  66946. _this.exitVR();
  66947. }
  66948. });
  66949. // Exiting VR mode double tapping the touch screen
  66950. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  66951. if (_this._isInVRMode) {
  66952. _this.exitVR();
  66953. }
  66954. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  66955. if (navigator.getVRDisplays) {
  66956. navigator.getVRDisplays().then(function (headsets) {
  66957. if (headsets.length > 0) {
  66958. _this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", _this._position, _this._scene);
  66959. _this._webVRsupportedAndReady = true;
  66960. }
  66961. document.body.appendChild(_this._btnVR);
  66962. });
  66963. }
  66964. else {
  66965. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  66966. document.body.appendChild(this._btnVR);
  66967. }
  66968. this._btnVR.addEventListener("click", function () {
  66969. _this.enterVR();
  66970. });
  66971. }
  66972. VRExperienceHelper.prototype.enterVR = function () {
  66973. // If WebVR is supported and a headset is connected
  66974. if (this._webVRsupportedAndReady) {
  66975. this._webVRCamera.position = this._position;
  66976. this._scene.activeCamera = this._webVRCamera;
  66977. }
  66978. else {
  66979. this._vrDeviceOrientationCamera.position = this._position;
  66980. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  66981. this._scene.getEngine().switchFullscreen(true);
  66982. }
  66983. this._scene.activeCamera.attachControl(this._canvas);
  66984. this._isInVRMode = true;
  66985. this._btnVR.style.display = "none";
  66986. };
  66987. VRExperienceHelper.prototype.exitVR = function () {
  66988. if (this._webVRsupportedAndReady) {
  66989. this._scene.getEngine().disableVR();
  66990. }
  66991. if (this._scene.activeCamera) {
  66992. this._position = this._scene.activeCamera.position;
  66993. }
  66994. this._deviceOrientationCamera.position = this._position;
  66995. this._scene.activeCamera = this._deviceOrientationCamera;
  66996. this._scene.activeCamera.attachControl(this._canvas);
  66997. this._isInVRMode = false;
  66998. this._btnVR.style.display = "";
  66999. };
  67000. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  67001. get: function () {
  67002. return this._position;
  67003. },
  67004. set: function (value) {
  67005. this._position = value;
  67006. this._scene.activeCamera.position = value;
  67007. },
  67008. enumerable: true,
  67009. configurable: true
  67010. });
  67011. VRExperienceHelper.prototype.dispose = function () {
  67012. if (this._isInVRMode) {
  67013. this.exitVR();
  67014. }
  67015. this._deviceOrientationCamera.dispose();
  67016. if (this._webVRCamera) {
  67017. this._webVRCamera.dispose();
  67018. }
  67019. if (this._vrDeviceOrientationCamera) {
  67020. this._vrDeviceOrientationCamera.dispose();
  67021. }
  67022. document.body.removeChild(this._btnVR);
  67023. };
  67024. VRExperienceHelper.prototype.getClassName = function () {
  67025. return "VRExperienceHelper";
  67026. };
  67027. return VRExperienceHelper;
  67028. }());
  67029. BABYLON.VRExperienceHelper = VRExperienceHelper;
  67030. })(BABYLON || (BABYLON = {}));
  67031. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  67032. // Mainly based on these 2 articles :
  67033. // 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
  67034. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  67035. var BABYLON;
  67036. (function (BABYLON) {
  67037. var JoystickAxis;
  67038. (function (JoystickAxis) {
  67039. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  67040. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  67041. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  67042. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  67043. var VirtualJoystick = (function () {
  67044. function VirtualJoystick(leftJoystick) {
  67045. var _this = this;
  67046. if (leftJoystick) {
  67047. this._leftJoystick = true;
  67048. }
  67049. else {
  67050. this._leftJoystick = false;
  67051. }
  67052. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  67053. VirtualJoystick._globalJoystickIndex++;
  67054. // By default left & right arrow keys are moving the X
  67055. // and up & down keys are moving the Y
  67056. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  67057. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  67058. this.reverseLeftRight = false;
  67059. this.reverseUpDown = false;
  67060. // collections of pointers
  67061. this._touches = new BABYLON.StringDictionary();
  67062. this.deltaPosition = BABYLON.Vector3.Zero();
  67063. this._joystickSensibility = 25;
  67064. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  67065. this._rotationSpeed = 25;
  67066. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  67067. this._rotateOnAxisRelativeToMesh = false;
  67068. this._onResize = function (evt) {
  67069. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  67070. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  67071. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  67072. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  67073. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  67074. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  67075. };
  67076. // injecting a canvas element on top of the canvas 3D game
  67077. if (!VirtualJoystick.vjCanvas) {
  67078. window.addEventListener("resize", this._onResize, false);
  67079. VirtualJoystick.vjCanvas = document.createElement("canvas");
  67080. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  67081. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  67082. VirtualJoystick.vjCanvas.width = window.innerWidth;
  67083. VirtualJoystick.vjCanvas.height = window.innerHeight;
  67084. VirtualJoystick.vjCanvas.style.width = "100%";
  67085. VirtualJoystick.vjCanvas.style.height = "100%";
  67086. VirtualJoystick.vjCanvas.style.position = "absolute";
  67087. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  67088. VirtualJoystick.vjCanvas.style.top = "0px";
  67089. VirtualJoystick.vjCanvas.style.left = "0px";
  67090. VirtualJoystick.vjCanvas.style.zIndex = "5";
  67091. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  67092. // Support for jQuery PEP polyfill
  67093. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  67094. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  67095. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  67096. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  67097. document.body.appendChild(VirtualJoystick.vjCanvas);
  67098. }
  67099. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  67100. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  67101. this.pressed = false;
  67102. // default joystick color
  67103. this._joystickColor = "cyan";
  67104. this._joystickPointerID = -1;
  67105. // current joystick position
  67106. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  67107. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  67108. // origin joystick position
  67109. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  67110. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  67111. this._onPointerDownHandlerRef = function (evt) {
  67112. _this._onPointerDown(evt);
  67113. };
  67114. this._onPointerMoveHandlerRef = function (evt) {
  67115. _this._onPointerMove(evt);
  67116. };
  67117. this._onPointerOutHandlerRef = function (evt) {
  67118. _this._onPointerUp(evt);
  67119. };
  67120. this._onPointerUpHandlerRef = function (evt) {
  67121. _this._onPointerUp(evt);
  67122. };
  67123. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  67124. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  67125. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  67126. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  67127. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  67128. evt.preventDefault(); // Disables system menu
  67129. }, false);
  67130. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  67131. }
  67132. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  67133. this._joystickSensibility = newJoystickSensibility;
  67134. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  67135. };
  67136. VirtualJoystick.prototype._onPointerDown = function (e) {
  67137. var positionOnScreenCondition;
  67138. e.preventDefault();
  67139. if (this._leftJoystick === true) {
  67140. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  67141. }
  67142. else {
  67143. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  67144. }
  67145. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  67146. // First contact will be dedicated to the virtual joystick
  67147. this._joystickPointerID = e.pointerId;
  67148. this._joystickPointerStartPos.x = e.clientX;
  67149. this._joystickPointerStartPos.y = e.clientY;
  67150. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  67151. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  67152. this._deltaJoystickVector.x = 0;
  67153. this._deltaJoystickVector.y = 0;
  67154. this.pressed = true;
  67155. this._touches.add(e.pointerId.toString(), e);
  67156. }
  67157. else {
  67158. // You can only trigger the action buttons with a joystick declared
  67159. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  67160. this._action();
  67161. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  67162. }
  67163. }
  67164. };
  67165. VirtualJoystick.prototype._onPointerMove = function (e) {
  67166. // If the current pointer is the one associated to the joystick (first touch contact)
  67167. if (this._joystickPointerID == e.pointerId) {
  67168. this._joystickPointerPos.x = e.clientX;
  67169. this._joystickPointerPos.y = e.clientY;
  67170. this._deltaJoystickVector = this._joystickPointerPos.clone();
  67171. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  67172. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  67173. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  67174. switch (this._axisTargetedByLeftAndRight) {
  67175. case JoystickAxis.X:
  67176. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  67177. break;
  67178. case JoystickAxis.Y:
  67179. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  67180. break;
  67181. case JoystickAxis.Z:
  67182. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  67183. break;
  67184. }
  67185. var directionUpDown = this.reverseUpDown ? 1 : -1;
  67186. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  67187. switch (this._axisTargetedByUpAndDown) {
  67188. case JoystickAxis.X:
  67189. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  67190. break;
  67191. case JoystickAxis.Y:
  67192. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  67193. break;
  67194. case JoystickAxis.Z:
  67195. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  67196. break;
  67197. }
  67198. }
  67199. else {
  67200. var data = this._touches.get(e.pointerId.toString());
  67201. if (data) {
  67202. data.x = e.clientX;
  67203. data.y = e.clientY;
  67204. }
  67205. }
  67206. };
  67207. VirtualJoystick.prototype._onPointerUp = function (e) {
  67208. if (this._joystickPointerID == e.pointerId) {
  67209. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  67210. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  67211. this._joystickPointerID = -1;
  67212. this.pressed = false;
  67213. }
  67214. else {
  67215. var touch = this._touches.get(e.pointerId.toString());
  67216. if (touch) {
  67217. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  67218. }
  67219. }
  67220. this._deltaJoystickVector.x = 0;
  67221. this._deltaJoystickVector.y = 0;
  67222. this._touches.remove(e.pointerId.toString());
  67223. };
  67224. /**
  67225. * Change the color of the virtual joystick
  67226. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  67227. */
  67228. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  67229. this._joystickColor = newColor;
  67230. };
  67231. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  67232. this._action = action;
  67233. };
  67234. // Define which axis you'd like to control for left & right
  67235. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  67236. switch (axis) {
  67237. case JoystickAxis.X:
  67238. case JoystickAxis.Y:
  67239. case JoystickAxis.Z:
  67240. this._axisTargetedByLeftAndRight = axis;
  67241. break;
  67242. default:
  67243. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  67244. break;
  67245. }
  67246. };
  67247. // Define which axis you'd like to control for up & down
  67248. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  67249. switch (axis) {
  67250. case JoystickAxis.X:
  67251. case JoystickAxis.Y:
  67252. case JoystickAxis.Z:
  67253. this._axisTargetedByUpAndDown = axis;
  67254. break;
  67255. default:
  67256. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  67257. break;
  67258. }
  67259. };
  67260. VirtualJoystick.prototype._clearCanvas = function () {
  67261. if (this._leftJoystick) {
  67262. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  67263. }
  67264. else {
  67265. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  67266. }
  67267. };
  67268. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  67269. var _this = this;
  67270. if (this.pressed) {
  67271. this._touches.forEach(function (key, touch) {
  67272. if (touch.pointerId === _this._joystickPointerID) {
  67273. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  67274. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  67275. VirtualJoystick.vjCanvasContext.beginPath();
  67276. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  67277. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67278. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  67279. VirtualJoystick.vjCanvasContext.stroke();
  67280. VirtualJoystick.vjCanvasContext.closePath();
  67281. VirtualJoystick.vjCanvasContext.beginPath();
  67282. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67283. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  67284. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  67285. VirtualJoystick.vjCanvasContext.stroke();
  67286. VirtualJoystick.vjCanvasContext.closePath();
  67287. VirtualJoystick.vjCanvasContext.beginPath();
  67288. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67289. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  67290. VirtualJoystick.vjCanvasContext.stroke();
  67291. VirtualJoystick.vjCanvasContext.closePath();
  67292. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  67293. }
  67294. else {
  67295. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  67296. VirtualJoystick.vjCanvasContext.beginPath();
  67297. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  67298. VirtualJoystick.vjCanvasContext.beginPath();
  67299. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  67300. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  67301. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  67302. VirtualJoystick.vjCanvasContext.stroke();
  67303. VirtualJoystick.vjCanvasContext.closePath();
  67304. touch.prevX = touch.x;
  67305. touch.prevY = touch.y;
  67306. }
  67307. ;
  67308. });
  67309. }
  67310. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  67311. };
  67312. VirtualJoystick.prototype.releaseCanvas = function () {
  67313. if (VirtualJoystick.vjCanvas) {
  67314. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  67315. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  67316. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  67317. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  67318. window.removeEventListener("resize", this._onResize);
  67319. document.body.removeChild(VirtualJoystick.vjCanvas);
  67320. VirtualJoystick.vjCanvas = null;
  67321. }
  67322. };
  67323. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  67324. VirtualJoystick._globalJoystickIndex = 0;
  67325. return VirtualJoystick;
  67326. }());
  67327. BABYLON.VirtualJoystick = VirtualJoystick;
  67328. })(BABYLON || (BABYLON = {}));
  67329. //# sourceMappingURL=babylon.virtualJoystick.js.map
  67330. var BABYLON;
  67331. (function (BABYLON) {
  67332. // We're mainly based on the logic defined into the FreeCamera code
  67333. var VirtualJoysticksCamera = (function (_super) {
  67334. __extends(VirtualJoysticksCamera, _super);
  67335. function VirtualJoysticksCamera(name, position, scene) {
  67336. var _this = _super.call(this, name, position, scene) || this;
  67337. _this.inputs.addVirtualJoystick();
  67338. return _this;
  67339. }
  67340. VirtualJoysticksCamera.prototype.getClassName = function () {
  67341. return "VirtualJoysticksCamera";
  67342. };
  67343. return VirtualJoysticksCamera;
  67344. }(BABYLON.FreeCamera));
  67345. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  67346. })(BABYLON || (BABYLON = {}));
  67347. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  67348. var BABYLON;
  67349. (function (BABYLON) {
  67350. var FreeCameraVirtualJoystickInput = (function () {
  67351. function FreeCameraVirtualJoystickInput() {
  67352. }
  67353. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  67354. return this._leftjoystick;
  67355. };
  67356. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  67357. return this._rightjoystick;
  67358. };
  67359. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  67360. if (this._leftjoystick) {
  67361. var camera = this.camera;
  67362. var speed = camera._computeLocalCameraSpeed() * 50;
  67363. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  67364. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  67365. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  67366. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  67367. if (!this._leftjoystick.pressed) {
  67368. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  67369. }
  67370. if (!this._rightjoystick.pressed) {
  67371. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  67372. }
  67373. }
  67374. };
  67375. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  67376. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  67377. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  67378. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  67379. this._leftjoystick.setJoystickSensibility(0.15);
  67380. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  67381. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  67382. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  67383. this._rightjoystick.reverseUpDown = true;
  67384. this._rightjoystick.setJoystickSensibility(0.05);
  67385. this._rightjoystick.setJoystickColor("yellow");
  67386. };
  67387. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  67388. this._leftjoystick.releaseCanvas();
  67389. this._rightjoystick.releaseCanvas();
  67390. };
  67391. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  67392. return "FreeCameraVirtualJoystickInput";
  67393. };
  67394. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  67395. return "virtualJoystick";
  67396. };
  67397. return FreeCameraVirtualJoystickInput;
  67398. }());
  67399. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  67400. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  67401. })(BABYLON || (BABYLON = {}));
  67402. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  67403. var BABYLON;
  67404. (function (BABYLON) {
  67405. var SimplificationSettings = (function () {
  67406. function SimplificationSettings(quality, distance, optimizeMesh) {
  67407. this.quality = quality;
  67408. this.distance = distance;
  67409. this.optimizeMesh = optimizeMesh;
  67410. }
  67411. return SimplificationSettings;
  67412. }());
  67413. BABYLON.SimplificationSettings = SimplificationSettings;
  67414. var SimplificationQueue = (function () {
  67415. function SimplificationQueue() {
  67416. this.running = false;
  67417. this._simplificationArray = [];
  67418. }
  67419. SimplificationQueue.prototype.addTask = function (task) {
  67420. this._simplificationArray.push(task);
  67421. };
  67422. SimplificationQueue.prototype.executeNext = function () {
  67423. var task = this._simplificationArray.pop();
  67424. if (task) {
  67425. this.running = true;
  67426. this.runSimplification(task);
  67427. }
  67428. else {
  67429. this.running = false;
  67430. }
  67431. };
  67432. SimplificationQueue.prototype.runSimplification = function (task) {
  67433. var _this = this;
  67434. if (task.parallelProcessing) {
  67435. //parallel simplifier
  67436. task.settings.forEach(function (setting) {
  67437. var simplifier = _this.getSimplifier(task);
  67438. simplifier.simplify(setting, function (newMesh) {
  67439. task.mesh.addLODLevel(setting.distance, newMesh);
  67440. newMesh.isVisible = true;
  67441. //check if it is the last
  67442. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  67443. //all done, run the success callback.
  67444. task.successCallback();
  67445. }
  67446. _this.executeNext();
  67447. });
  67448. });
  67449. }
  67450. else {
  67451. //single simplifier.
  67452. var simplifier = this.getSimplifier(task);
  67453. var runDecimation = function (setting, callback) {
  67454. simplifier.simplify(setting, function (newMesh) {
  67455. task.mesh.addLODLevel(setting.distance, newMesh);
  67456. newMesh.isVisible = true;
  67457. //run the next quality level
  67458. callback();
  67459. });
  67460. };
  67461. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  67462. runDecimation(task.settings[loop.index], function () {
  67463. loop.executeNext();
  67464. });
  67465. }, function () {
  67466. //execution ended, run the success callback.
  67467. if (task.successCallback) {
  67468. task.successCallback();
  67469. }
  67470. _this.executeNext();
  67471. });
  67472. }
  67473. };
  67474. SimplificationQueue.prototype.getSimplifier = function (task) {
  67475. switch (task.simplificationType) {
  67476. case SimplificationType.QUADRATIC:
  67477. default:
  67478. return new QuadraticErrorSimplification(task.mesh);
  67479. }
  67480. };
  67481. return SimplificationQueue;
  67482. }());
  67483. BABYLON.SimplificationQueue = SimplificationQueue;
  67484. /**
  67485. * The implemented types of simplification.
  67486. * At the moment only Quadratic Error Decimation is implemented.
  67487. */
  67488. var SimplificationType;
  67489. (function (SimplificationType) {
  67490. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  67491. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  67492. var DecimationTriangle = (function () {
  67493. function DecimationTriangle(vertices) {
  67494. this.vertices = vertices;
  67495. this.error = new Array(4);
  67496. this.deleted = false;
  67497. this.isDirty = false;
  67498. this.deletePending = false;
  67499. this.borderFactor = 0;
  67500. }
  67501. return DecimationTriangle;
  67502. }());
  67503. BABYLON.DecimationTriangle = DecimationTriangle;
  67504. var DecimationVertex = (function () {
  67505. function DecimationVertex(position, id) {
  67506. this.position = position;
  67507. this.id = id;
  67508. this.isBorder = true;
  67509. this.q = new QuadraticMatrix();
  67510. this.triangleCount = 0;
  67511. this.triangleStart = 0;
  67512. this.originalOffsets = [];
  67513. }
  67514. DecimationVertex.prototype.updatePosition = function (newPosition) {
  67515. this.position.copyFrom(newPosition);
  67516. };
  67517. return DecimationVertex;
  67518. }());
  67519. BABYLON.DecimationVertex = DecimationVertex;
  67520. var QuadraticMatrix = (function () {
  67521. function QuadraticMatrix(data) {
  67522. this.data = new Array(10);
  67523. for (var i = 0; i < 10; ++i) {
  67524. if (data && data[i]) {
  67525. this.data[i] = data[i];
  67526. }
  67527. else {
  67528. this.data[i] = 0;
  67529. }
  67530. }
  67531. }
  67532. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  67533. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  67534. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  67535. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  67536. return det;
  67537. };
  67538. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  67539. for (var i = 0; i < 10; ++i) {
  67540. this.data[i] += matrix.data[i];
  67541. }
  67542. };
  67543. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  67544. for (var i = 0; i < 10; ++i) {
  67545. this.data[i] += data[i];
  67546. }
  67547. };
  67548. QuadraticMatrix.prototype.add = function (matrix) {
  67549. var m = new QuadraticMatrix();
  67550. for (var i = 0; i < 10; ++i) {
  67551. m.data[i] = this.data[i] + matrix.data[i];
  67552. }
  67553. return m;
  67554. };
  67555. QuadraticMatrix.FromData = function (a, b, c, d) {
  67556. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  67557. };
  67558. //returning an array to avoid garbage collection
  67559. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  67560. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  67561. };
  67562. return QuadraticMatrix;
  67563. }());
  67564. BABYLON.QuadraticMatrix = QuadraticMatrix;
  67565. var Reference = (function () {
  67566. function Reference(vertexId, triangleId) {
  67567. this.vertexId = vertexId;
  67568. this.triangleId = triangleId;
  67569. }
  67570. return Reference;
  67571. }());
  67572. BABYLON.Reference = Reference;
  67573. /**
  67574. * An implementation of the Quadratic Error simplification algorithm.
  67575. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  67576. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  67577. * @author RaananW
  67578. */
  67579. var QuadraticErrorSimplification = (function () {
  67580. function QuadraticErrorSimplification(_mesh) {
  67581. this._mesh = _mesh;
  67582. this.initialized = false;
  67583. this.syncIterations = 5000;
  67584. this.aggressiveness = 7;
  67585. this.decimationIterations = 100;
  67586. this.boundingBoxEpsilon = BABYLON.Epsilon;
  67587. }
  67588. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  67589. var _this = this;
  67590. this.initDecimatedMesh();
  67591. //iterating through the submeshes array, one after the other.
  67592. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  67593. _this.initWithMesh(loop.index, function () {
  67594. _this.runDecimation(settings, loop.index, function () {
  67595. loop.executeNext();
  67596. });
  67597. }, settings.optimizeMesh);
  67598. }, function () {
  67599. setTimeout(function () {
  67600. successCallback(_this._reconstructedMesh);
  67601. }, 0);
  67602. });
  67603. };
  67604. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  67605. var _this = this;
  67606. var gCount = 0;
  67607. triangle.vertices.forEach(function (vertex) {
  67608. var count = 0;
  67609. var vPos = vertex.position;
  67610. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  67611. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  67612. ++count;
  67613. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  67614. ++count;
  67615. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  67616. ++count;
  67617. if (count > 1) {
  67618. ++gCount;
  67619. }
  67620. ;
  67621. });
  67622. if (gCount > 1) {
  67623. console.log(triangle, gCount);
  67624. }
  67625. return gCount > 1;
  67626. };
  67627. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  67628. var _this = this;
  67629. var targetCount = ~~(this.triangles.length * settings.quality);
  67630. var deletedTriangles = 0;
  67631. var triangleCount = this.triangles.length;
  67632. var iterationFunction = function (iteration, callback) {
  67633. setTimeout(function () {
  67634. if (iteration % 5 === 0) {
  67635. _this.updateMesh(iteration === 0);
  67636. }
  67637. for (var i = 0; i < _this.triangles.length; ++i) {
  67638. _this.triangles[i].isDirty = false;
  67639. }
  67640. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  67641. var trianglesIterator = function (i) {
  67642. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  67643. var t = _this.triangles[tIdx];
  67644. if (!t)
  67645. return;
  67646. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  67647. return;
  67648. }
  67649. for (var j = 0; j < 3; ++j) {
  67650. if (t.error[j] < threshold) {
  67651. var deleted0 = [];
  67652. var deleted1 = [];
  67653. var v0 = t.vertices[j];
  67654. var v1 = t.vertices[(j + 1) % 3];
  67655. if (v0.isBorder || v1.isBorder)
  67656. continue;
  67657. var p = BABYLON.Vector3.Zero();
  67658. var n = BABYLON.Vector3.Zero();
  67659. var uv = BABYLON.Vector2.Zero();
  67660. var color = new BABYLON.Color4(0, 0, 0, 1);
  67661. _this.calculateError(v0, v1, p, n, uv, color);
  67662. var delTr = [];
  67663. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  67664. continue;
  67665. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  67666. continue;
  67667. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  67668. continue;
  67669. var uniqueArray = [];
  67670. delTr.forEach(function (deletedT) {
  67671. if (uniqueArray.indexOf(deletedT) === -1) {
  67672. deletedT.deletePending = true;
  67673. uniqueArray.push(deletedT);
  67674. }
  67675. });
  67676. if (uniqueArray.length % 2 !== 0) {
  67677. continue;
  67678. }
  67679. v0.q = v1.q.add(v0.q);
  67680. v0.updatePosition(p);
  67681. var tStart = _this.references.length;
  67682. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  67683. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  67684. var tCount = _this.references.length - tStart;
  67685. if (tCount <= v0.triangleCount) {
  67686. if (tCount) {
  67687. for (var c = 0; c < tCount; c++) {
  67688. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  67689. }
  67690. }
  67691. }
  67692. else {
  67693. v0.triangleStart = tStart;
  67694. }
  67695. v0.triangleCount = tCount;
  67696. break;
  67697. }
  67698. }
  67699. };
  67700. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  67701. }, 0);
  67702. };
  67703. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  67704. if (triangleCount - deletedTriangles <= targetCount)
  67705. loop.breakLoop();
  67706. else {
  67707. iterationFunction(loop.index, function () {
  67708. loop.executeNext();
  67709. });
  67710. }
  67711. }, function () {
  67712. setTimeout(function () {
  67713. //reconstruct this part of the mesh
  67714. _this.reconstructMesh(submeshIndex);
  67715. successCallback();
  67716. }, 0);
  67717. });
  67718. };
  67719. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  67720. var _this = this;
  67721. this.vertices = [];
  67722. this.triangles = [];
  67723. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67724. var indices = this._mesh.getIndices();
  67725. var submesh = this._mesh.subMeshes[submeshIndex];
  67726. var findInVertices = function (positionToSearch) {
  67727. if (optimizeMesh) {
  67728. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  67729. if (_this.vertices[ii].position.equals(positionToSearch)) {
  67730. return _this.vertices[ii];
  67731. }
  67732. }
  67733. }
  67734. return null;
  67735. };
  67736. var vertexReferences = [];
  67737. var vertexInit = function (i) {
  67738. var offset = i + submesh.verticesStart;
  67739. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  67740. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  67741. vertex.originalOffsets.push(offset);
  67742. if (vertex.id === _this.vertices.length) {
  67743. _this.vertices.push(vertex);
  67744. }
  67745. vertexReferences.push(vertex.id);
  67746. };
  67747. //var totalVertices = mesh.getTotalVertices();
  67748. var totalVertices = submesh.verticesCount;
  67749. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  67750. var indicesInit = function (i) {
  67751. var offset = (submesh.indexStart / 3) + i;
  67752. var pos = (offset * 3);
  67753. var i0 = indices[pos + 0];
  67754. var i1 = indices[pos + 1];
  67755. var i2 = indices[pos + 2];
  67756. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  67757. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  67758. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  67759. var triangle = new DecimationTriangle([v0, v1, v2]);
  67760. triangle.originalOffset = pos;
  67761. _this.triangles.push(triangle);
  67762. };
  67763. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  67764. _this.init(callback);
  67765. });
  67766. });
  67767. };
  67768. QuadraticErrorSimplification.prototype.init = function (callback) {
  67769. var _this = this;
  67770. var triangleInit1 = function (i) {
  67771. var t = _this.triangles[i];
  67772. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  67773. for (var j = 0; j < 3; j++) {
  67774. 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))));
  67775. }
  67776. };
  67777. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  67778. var triangleInit2 = function (i) {
  67779. var t = _this.triangles[i];
  67780. for (var j = 0; j < 3; ++j) {
  67781. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  67782. }
  67783. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  67784. };
  67785. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  67786. _this.initialized = true;
  67787. callback();
  67788. });
  67789. });
  67790. };
  67791. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  67792. var newTriangles = [];
  67793. var i;
  67794. for (i = 0; i < this.vertices.length; ++i) {
  67795. this.vertices[i].triangleCount = 0;
  67796. }
  67797. var t;
  67798. var j;
  67799. for (i = 0; i < this.triangles.length; ++i) {
  67800. if (!this.triangles[i].deleted) {
  67801. t = this.triangles[i];
  67802. for (j = 0; j < 3; ++j) {
  67803. t.vertices[j].triangleCount = 1;
  67804. }
  67805. newTriangles.push(t);
  67806. }
  67807. }
  67808. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  67809. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  67810. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  67811. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  67812. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67813. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67814. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67815. var vertexCount = 0;
  67816. for (i = 0; i < this.vertices.length; ++i) {
  67817. var vertex = this.vertices[i];
  67818. vertex.id = vertexCount;
  67819. if (vertex.triangleCount) {
  67820. vertex.originalOffsets.forEach(function (originalOffset) {
  67821. newPositionData.push(vertex.position.x);
  67822. newPositionData.push(vertex.position.y);
  67823. newPositionData.push(vertex.position.z);
  67824. newNormalData.push(normalData[originalOffset * 3]);
  67825. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  67826. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  67827. if (uvs && uvs.length) {
  67828. newUVsData.push(uvs[(originalOffset * 2)]);
  67829. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  67830. }
  67831. else if (colorsData && colorsData.length) {
  67832. newColorsData.push(colorsData[(originalOffset * 4)]);
  67833. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  67834. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  67835. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  67836. }
  67837. ++vertexCount;
  67838. });
  67839. }
  67840. }
  67841. var startingIndex = this._reconstructedMesh.getTotalIndices();
  67842. var startingVertex = this._reconstructedMesh.getTotalVertices();
  67843. var submeshesArray = this._reconstructedMesh.subMeshes;
  67844. this._reconstructedMesh.subMeshes = [];
  67845. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  67846. var originalIndices = this._mesh.getIndices();
  67847. for (i = 0; i < newTriangles.length; ++i) {
  67848. t = newTriangles[i]; //now get the new referencing point for each vertex
  67849. [0, 1, 2].forEach(function (idx) {
  67850. var id = originalIndices[t.originalOffset + idx];
  67851. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  67852. if (offset < 0)
  67853. offset = 0;
  67854. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  67855. });
  67856. }
  67857. //overwriting the old vertex buffers and indices.
  67858. this._reconstructedMesh.setIndices(newIndicesArray);
  67859. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  67860. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  67861. if (newUVsData.length > 0)
  67862. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  67863. if (newColorsData.length > 0)
  67864. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  67865. //create submesh
  67866. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  67867. if (submeshIndex > 0) {
  67868. this._reconstructedMesh.subMeshes = [];
  67869. submeshesArray.forEach(function (submesh) {
  67870. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  67871. });
  67872. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  67873. }
  67874. };
  67875. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  67876. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  67877. this._reconstructedMesh.material = this._mesh.material;
  67878. this._reconstructedMesh.parent = this._mesh.parent;
  67879. this._reconstructedMesh.isVisible = false;
  67880. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  67881. };
  67882. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  67883. for (var i = 0; i < vertex1.triangleCount; ++i) {
  67884. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  67885. if (t.deleted)
  67886. continue;
  67887. var s = this.references[vertex1.triangleStart + i].vertexId;
  67888. var v1 = t.vertices[(s + 1) % 3];
  67889. var v2 = t.vertices[(s + 2) % 3];
  67890. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  67891. deletedArray[i] = true;
  67892. delTr.push(t);
  67893. continue;
  67894. }
  67895. var d1 = v1.position.subtract(point);
  67896. d1 = d1.normalize();
  67897. var d2 = v2.position.subtract(point);
  67898. d2 = d2.normalize();
  67899. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  67900. return true;
  67901. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  67902. deletedArray[i] = false;
  67903. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  67904. return true;
  67905. }
  67906. return false;
  67907. };
  67908. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  67909. var newDeleted = deletedTriangles;
  67910. for (var i = 0; i < vertex.triangleCount; ++i) {
  67911. var ref = this.references[vertex.triangleStart + i];
  67912. var t = this.triangles[ref.triangleId];
  67913. if (t.deleted)
  67914. continue;
  67915. if (deletedArray[i] && t.deletePending) {
  67916. t.deleted = true;
  67917. newDeleted++;
  67918. continue;
  67919. }
  67920. t.vertices[ref.vertexId] = origVertex;
  67921. t.isDirty = true;
  67922. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  67923. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  67924. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  67925. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  67926. this.references.push(ref);
  67927. }
  67928. return newDeleted;
  67929. };
  67930. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  67931. for (var i = 0; i < this.vertices.length; ++i) {
  67932. var vCount = [];
  67933. var vId = [];
  67934. var v = this.vertices[i];
  67935. var j;
  67936. for (j = 0; j < v.triangleCount; ++j) {
  67937. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  67938. for (var ii = 0; ii < 3; ii++) {
  67939. var ofs = 0;
  67940. var vv = triangle.vertices[ii];
  67941. while (ofs < vCount.length) {
  67942. if (vId[ofs] === vv.id)
  67943. break;
  67944. ++ofs;
  67945. }
  67946. if (ofs === vCount.length) {
  67947. vCount.push(1);
  67948. vId.push(vv.id);
  67949. }
  67950. else {
  67951. vCount[ofs]++;
  67952. }
  67953. }
  67954. }
  67955. for (j = 0; j < vCount.length; ++j) {
  67956. if (vCount[j] === 1) {
  67957. this.vertices[vId[j]].isBorder = true;
  67958. }
  67959. else {
  67960. this.vertices[vId[j]].isBorder = false;
  67961. }
  67962. }
  67963. }
  67964. };
  67965. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  67966. if (identifyBorders === void 0) { identifyBorders = false; }
  67967. var i;
  67968. if (!identifyBorders) {
  67969. var newTrianglesVector = [];
  67970. for (i = 0; i < this.triangles.length; ++i) {
  67971. if (!this.triangles[i].deleted) {
  67972. newTrianglesVector.push(this.triangles[i]);
  67973. }
  67974. }
  67975. this.triangles = newTrianglesVector;
  67976. }
  67977. for (i = 0; i < this.vertices.length; ++i) {
  67978. this.vertices[i].triangleCount = 0;
  67979. this.vertices[i].triangleStart = 0;
  67980. }
  67981. var t;
  67982. var j;
  67983. var v;
  67984. for (i = 0; i < this.triangles.length; ++i) {
  67985. t = this.triangles[i];
  67986. for (j = 0; j < 3; ++j) {
  67987. v = t.vertices[j];
  67988. v.triangleCount++;
  67989. }
  67990. }
  67991. var tStart = 0;
  67992. for (i = 0; i < this.vertices.length; ++i) {
  67993. this.vertices[i].triangleStart = tStart;
  67994. tStart += this.vertices[i].triangleCount;
  67995. this.vertices[i].triangleCount = 0;
  67996. }
  67997. var newReferences = new Array(this.triangles.length * 3);
  67998. for (i = 0; i < this.triangles.length; ++i) {
  67999. t = this.triangles[i];
  68000. for (j = 0; j < 3; ++j) {
  68001. v = t.vertices[j];
  68002. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  68003. v.triangleCount++;
  68004. }
  68005. }
  68006. this.references = newReferences;
  68007. if (identifyBorders) {
  68008. this.identifyBorder();
  68009. }
  68010. };
  68011. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  68012. var x = point.x;
  68013. var y = point.y;
  68014. var z = point.z;
  68015. 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
  68016. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  68017. };
  68018. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  68019. var q = vertex1.q.add(vertex2.q);
  68020. var border = vertex1.isBorder && vertex2.isBorder;
  68021. var error = 0;
  68022. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  68023. if (qDet !== 0 && !border) {
  68024. if (!pointResult) {
  68025. pointResult = BABYLON.Vector3.Zero();
  68026. }
  68027. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  68028. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  68029. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  68030. error = this.vertexError(q, pointResult);
  68031. }
  68032. else {
  68033. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  68034. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  68035. var error1 = this.vertexError(q, vertex1.position);
  68036. var error2 = this.vertexError(q, vertex2.position);
  68037. var error3 = this.vertexError(q, p3);
  68038. error = Math.min(error1, error2, error3);
  68039. if (error === error1) {
  68040. if (pointResult) {
  68041. pointResult.copyFrom(vertex1.position);
  68042. }
  68043. }
  68044. else if (error === error2) {
  68045. if (pointResult) {
  68046. pointResult.copyFrom(vertex2.position);
  68047. }
  68048. }
  68049. else {
  68050. if (pointResult) {
  68051. pointResult.copyFrom(p3);
  68052. }
  68053. }
  68054. }
  68055. return error;
  68056. };
  68057. return QuadraticErrorSimplification;
  68058. }());
  68059. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  68060. })(BABYLON || (BABYLON = {}));
  68061. //# sourceMappingURL=babylon.meshSimplification.js.map
  68062. var BABYLON;
  68063. (function (BABYLON) {
  68064. var Internals;
  68065. (function (Internals) {
  68066. var MeshLODLevel = (function () {
  68067. function MeshLODLevel(distance, mesh) {
  68068. this.distance = distance;
  68069. this.mesh = mesh;
  68070. }
  68071. return MeshLODLevel;
  68072. }());
  68073. Internals.MeshLODLevel = MeshLODLevel;
  68074. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68075. })(BABYLON || (BABYLON = {}));
  68076. //# sourceMappingURL=babylon.meshLODLevel.js.map
  68077. var BABYLON;
  68078. (function (BABYLON) {
  68079. // Standard optimizations
  68080. var SceneOptimization = (function () {
  68081. function SceneOptimization(priority) {
  68082. if (priority === void 0) { priority = 0; }
  68083. this.priority = priority;
  68084. this.apply = function (scene) {
  68085. return true; // Return true if everything that can be done was applied
  68086. };
  68087. }
  68088. return SceneOptimization;
  68089. }());
  68090. BABYLON.SceneOptimization = SceneOptimization;
  68091. var TextureOptimization = (function (_super) {
  68092. __extends(TextureOptimization, _super);
  68093. function TextureOptimization(priority, maximumSize) {
  68094. if (priority === void 0) { priority = 0; }
  68095. if (maximumSize === void 0) { maximumSize = 1024; }
  68096. var _this = _super.call(this, priority) || this;
  68097. _this.priority = priority;
  68098. _this.maximumSize = maximumSize;
  68099. _this.apply = function (scene) {
  68100. var allDone = true;
  68101. for (var index = 0; index < scene.textures.length; index++) {
  68102. var texture = scene.textures[index];
  68103. if (!texture.canRescale || texture.getContext) {
  68104. continue;
  68105. }
  68106. var currentSize = texture.getSize();
  68107. var maxDimension = Math.max(currentSize.width, currentSize.height);
  68108. if (maxDimension > _this.maximumSize) {
  68109. texture.scale(0.5);
  68110. allDone = false;
  68111. }
  68112. }
  68113. return allDone;
  68114. };
  68115. return _this;
  68116. }
  68117. return TextureOptimization;
  68118. }(SceneOptimization));
  68119. BABYLON.TextureOptimization = TextureOptimization;
  68120. var HardwareScalingOptimization = (function (_super) {
  68121. __extends(HardwareScalingOptimization, _super);
  68122. function HardwareScalingOptimization(priority, maximumScale) {
  68123. if (priority === void 0) { priority = 0; }
  68124. if (maximumScale === void 0) { maximumScale = 2; }
  68125. var _this = _super.call(this, priority) || this;
  68126. _this.priority = priority;
  68127. _this.maximumScale = maximumScale;
  68128. _this._currentScale = 1;
  68129. _this.apply = function (scene) {
  68130. _this._currentScale++;
  68131. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  68132. return _this._currentScale >= _this.maximumScale;
  68133. };
  68134. return _this;
  68135. }
  68136. return HardwareScalingOptimization;
  68137. }(SceneOptimization));
  68138. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  68139. var ShadowsOptimization = (function (_super) {
  68140. __extends(ShadowsOptimization, _super);
  68141. function ShadowsOptimization() {
  68142. var _this = _super !== null && _super.apply(this, arguments) || this;
  68143. _this.apply = function (scene) {
  68144. scene.shadowsEnabled = false;
  68145. return true;
  68146. };
  68147. return _this;
  68148. }
  68149. return ShadowsOptimization;
  68150. }(SceneOptimization));
  68151. BABYLON.ShadowsOptimization = ShadowsOptimization;
  68152. var PostProcessesOptimization = (function (_super) {
  68153. __extends(PostProcessesOptimization, _super);
  68154. function PostProcessesOptimization() {
  68155. var _this = _super !== null && _super.apply(this, arguments) || this;
  68156. _this.apply = function (scene) {
  68157. scene.postProcessesEnabled = false;
  68158. return true;
  68159. };
  68160. return _this;
  68161. }
  68162. return PostProcessesOptimization;
  68163. }(SceneOptimization));
  68164. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  68165. var LensFlaresOptimization = (function (_super) {
  68166. __extends(LensFlaresOptimization, _super);
  68167. function LensFlaresOptimization() {
  68168. var _this = _super !== null && _super.apply(this, arguments) || this;
  68169. _this.apply = function (scene) {
  68170. scene.lensFlaresEnabled = false;
  68171. return true;
  68172. };
  68173. return _this;
  68174. }
  68175. return LensFlaresOptimization;
  68176. }(SceneOptimization));
  68177. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  68178. var ParticlesOptimization = (function (_super) {
  68179. __extends(ParticlesOptimization, _super);
  68180. function ParticlesOptimization() {
  68181. var _this = _super !== null && _super.apply(this, arguments) || this;
  68182. _this.apply = function (scene) {
  68183. scene.particlesEnabled = false;
  68184. return true;
  68185. };
  68186. return _this;
  68187. }
  68188. return ParticlesOptimization;
  68189. }(SceneOptimization));
  68190. BABYLON.ParticlesOptimization = ParticlesOptimization;
  68191. var RenderTargetsOptimization = (function (_super) {
  68192. __extends(RenderTargetsOptimization, _super);
  68193. function RenderTargetsOptimization() {
  68194. var _this = _super !== null && _super.apply(this, arguments) || this;
  68195. _this.apply = function (scene) {
  68196. scene.renderTargetsEnabled = false;
  68197. return true;
  68198. };
  68199. return _this;
  68200. }
  68201. return RenderTargetsOptimization;
  68202. }(SceneOptimization));
  68203. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  68204. var MergeMeshesOptimization = (function (_super) {
  68205. __extends(MergeMeshesOptimization, _super);
  68206. function MergeMeshesOptimization() {
  68207. var _this = _super !== null && _super.apply(this, arguments) || this;
  68208. _this._canBeMerged = function (abstractMesh) {
  68209. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  68210. return false;
  68211. }
  68212. var mesh = abstractMesh;
  68213. if (!mesh.isVisible || !mesh.isEnabled()) {
  68214. return false;
  68215. }
  68216. if (mesh.instances.length > 0) {
  68217. return false;
  68218. }
  68219. if (mesh.skeleton || mesh.hasLODLevels) {
  68220. return false;
  68221. }
  68222. if (mesh.parent) {
  68223. return false;
  68224. }
  68225. return true;
  68226. };
  68227. _this.apply = function (scene, updateSelectionTree) {
  68228. var globalPool = scene.meshes.slice(0);
  68229. var globalLength = globalPool.length;
  68230. for (var index = 0; index < globalLength; index++) {
  68231. var currentPool = new Array();
  68232. var current = globalPool[index];
  68233. // Checks
  68234. if (!_this._canBeMerged(current)) {
  68235. continue;
  68236. }
  68237. currentPool.push(current);
  68238. // Find compatible meshes
  68239. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  68240. var otherMesh = globalPool[subIndex];
  68241. if (!_this._canBeMerged(otherMesh)) {
  68242. continue;
  68243. }
  68244. if (otherMesh.material !== current.material) {
  68245. continue;
  68246. }
  68247. if (otherMesh.checkCollisions !== current.checkCollisions) {
  68248. continue;
  68249. }
  68250. currentPool.push(otherMesh);
  68251. globalLength--;
  68252. globalPool.splice(subIndex, 1);
  68253. subIndex--;
  68254. }
  68255. if (currentPool.length < 2) {
  68256. continue;
  68257. }
  68258. // Merge meshes
  68259. BABYLON.Mesh.MergeMeshes(currentPool);
  68260. }
  68261. if (updateSelectionTree != undefined) {
  68262. if (updateSelectionTree) {
  68263. scene.createOrUpdateSelectionOctree();
  68264. }
  68265. }
  68266. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  68267. scene.createOrUpdateSelectionOctree();
  68268. }
  68269. return true;
  68270. };
  68271. return _this;
  68272. }
  68273. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  68274. get: function () {
  68275. return MergeMeshesOptimization._UpdateSelectionTree;
  68276. },
  68277. set: function (value) {
  68278. MergeMeshesOptimization._UpdateSelectionTree = value;
  68279. },
  68280. enumerable: true,
  68281. configurable: true
  68282. });
  68283. MergeMeshesOptimization._UpdateSelectionTree = false;
  68284. return MergeMeshesOptimization;
  68285. }(SceneOptimization));
  68286. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  68287. // Options
  68288. var SceneOptimizerOptions = (function () {
  68289. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  68290. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  68291. if (trackerDuration === void 0) { trackerDuration = 2000; }
  68292. this.targetFrameRate = targetFrameRate;
  68293. this.trackerDuration = trackerDuration;
  68294. this.optimizations = new Array();
  68295. }
  68296. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  68297. var result = new SceneOptimizerOptions(targetFrameRate);
  68298. var priority = 0;
  68299. result.optimizations.push(new MergeMeshesOptimization(priority));
  68300. result.optimizations.push(new ShadowsOptimization(priority));
  68301. result.optimizations.push(new LensFlaresOptimization(priority));
  68302. // Next priority
  68303. priority++;
  68304. result.optimizations.push(new PostProcessesOptimization(priority));
  68305. result.optimizations.push(new ParticlesOptimization(priority));
  68306. // Next priority
  68307. priority++;
  68308. result.optimizations.push(new TextureOptimization(priority, 1024));
  68309. return result;
  68310. };
  68311. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  68312. var result = new SceneOptimizerOptions(targetFrameRate);
  68313. var priority = 0;
  68314. result.optimizations.push(new MergeMeshesOptimization(priority));
  68315. result.optimizations.push(new ShadowsOptimization(priority));
  68316. result.optimizations.push(new LensFlaresOptimization(priority));
  68317. // Next priority
  68318. priority++;
  68319. result.optimizations.push(new PostProcessesOptimization(priority));
  68320. result.optimizations.push(new ParticlesOptimization(priority));
  68321. // Next priority
  68322. priority++;
  68323. result.optimizations.push(new TextureOptimization(priority, 512));
  68324. // Next priority
  68325. priority++;
  68326. result.optimizations.push(new RenderTargetsOptimization(priority));
  68327. // Next priority
  68328. priority++;
  68329. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  68330. return result;
  68331. };
  68332. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  68333. var result = new SceneOptimizerOptions(targetFrameRate);
  68334. var priority = 0;
  68335. result.optimizations.push(new MergeMeshesOptimization(priority));
  68336. result.optimizations.push(new ShadowsOptimization(priority));
  68337. result.optimizations.push(new LensFlaresOptimization(priority));
  68338. // Next priority
  68339. priority++;
  68340. result.optimizations.push(new PostProcessesOptimization(priority));
  68341. result.optimizations.push(new ParticlesOptimization(priority));
  68342. // Next priority
  68343. priority++;
  68344. result.optimizations.push(new TextureOptimization(priority, 256));
  68345. // Next priority
  68346. priority++;
  68347. result.optimizations.push(new RenderTargetsOptimization(priority));
  68348. // Next priority
  68349. priority++;
  68350. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  68351. return result;
  68352. };
  68353. return SceneOptimizerOptions;
  68354. }());
  68355. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  68356. // Scene optimizer tool
  68357. var SceneOptimizer = (function () {
  68358. function SceneOptimizer() {
  68359. }
  68360. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  68361. // TODO: add an epsilon
  68362. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  68363. if (onSuccess) {
  68364. onSuccess();
  68365. }
  68366. return;
  68367. }
  68368. // Apply current level of optimizations
  68369. var allDone = true;
  68370. var noOptimizationApplied = true;
  68371. for (var index = 0; index < options.optimizations.length; index++) {
  68372. var optimization = options.optimizations[index];
  68373. if (optimization.priority === currentPriorityLevel) {
  68374. noOptimizationApplied = false;
  68375. allDone = allDone && optimization.apply(scene);
  68376. }
  68377. }
  68378. // If no optimization was applied, this is a failure :(
  68379. if (noOptimizationApplied) {
  68380. if (onFailure) {
  68381. onFailure();
  68382. }
  68383. return;
  68384. }
  68385. // If all optimizations were done, move to next level
  68386. if (allDone) {
  68387. currentPriorityLevel++;
  68388. }
  68389. // Let's the system running for a specific amount of time before checking FPS
  68390. scene.executeWhenReady(function () {
  68391. setTimeout(function () {
  68392. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  68393. }, options.trackerDuration);
  68394. });
  68395. };
  68396. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  68397. if (!options) {
  68398. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  68399. }
  68400. // Let's the system running for a specific amount of time before checking FPS
  68401. scene.executeWhenReady(function () {
  68402. setTimeout(function () {
  68403. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  68404. }, options.trackerDuration);
  68405. });
  68406. };
  68407. return SceneOptimizer;
  68408. }());
  68409. BABYLON.SceneOptimizer = SceneOptimizer;
  68410. })(BABYLON || (BABYLON = {}));
  68411. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  68412. var BABYLON;
  68413. (function (BABYLON) {
  68414. var OutlineRenderer = (function () {
  68415. function OutlineRenderer(scene) {
  68416. this.zOffset = 1;
  68417. this._scene = scene;
  68418. }
  68419. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  68420. var _this = this;
  68421. if (useOverlay === void 0) { useOverlay = false; }
  68422. var scene = this._scene;
  68423. var engine = this._scene.getEngine();
  68424. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68425. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  68426. return;
  68427. }
  68428. var mesh = subMesh.getRenderingMesh();
  68429. var material = subMesh.getMaterial();
  68430. engine.enableEffect(this._effect);
  68431. // Logarithmic depth
  68432. if (material.useLogarithmicDepth) {
  68433. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  68434. }
  68435. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  68436. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  68437. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68438. // Bones
  68439. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68440. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68441. }
  68442. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68443. // Alpha test
  68444. if (material && material.needAlphaTesting()) {
  68445. var alphaTexture = material.getAlphaTestTexture();
  68446. if (alphaTexture) {
  68447. this._effect.setTexture("diffuseSampler", alphaTexture);
  68448. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68449. }
  68450. }
  68451. engine.setZOffset(-this.zOffset);
  68452. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  68453. engine.setZOffset(0);
  68454. };
  68455. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  68456. var defines = [];
  68457. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68458. var mesh = subMesh.getMesh();
  68459. var material = subMesh.getMaterial();
  68460. if (material) {
  68461. // Alpha test
  68462. if (material.needAlphaTesting()) {
  68463. defines.push("#define ALPHATEST");
  68464. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68465. attribs.push(BABYLON.VertexBuffer.UVKind);
  68466. defines.push("#define UV1");
  68467. }
  68468. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68469. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68470. defines.push("#define UV2");
  68471. }
  68472. }
  68473. //Logarithmic depth
  68474. if (material.useLogarithmicDepth) {
  68475. defines.push("#define LOGARITHMICDEPTH");
  68476. }
  68477. }
  68478. // Bones
  68479. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68480. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68481. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68482. if (mesh.numBoneInfluencers > 4) {
  68483. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68484. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68485. }
  68486. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68487. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68488. }
  68489. else {
  68490. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68491. }
  68492. // Instances
  68493. if (useInstances) {
  68494. defines.push("#define INSTANCES");
  68495. attribs.push("world0");
  68496. attribs.push("world1");
  68497. attribs.push("world2");
  68498. attribs.push("world3");
  68499. }
  68500. // Get correct effect
  68501. var join = defines.join("\n");
  68502. if (this._cachedDefines !== join) {
  68503. this._cachedDefines = join;
  68504. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  68505. }
  68506. return this._effect.isReady();
  68507. };
  68508. return OutlineRenderer;
  68509. }());
  68510. BABYLON.OutlineRenderer = OutlineRenderer;
  68511. })(BABYLON || (BABYLON = {}));
  68512. //# sourceMappingURL=babylon.outlineRenderer.js.map
  68513. var BABYLON;
  68514. (function (BABYLON) {
  68515. var FaceAdjacencies = (function () {
  68516. function FaceAdjacencies() {
  68517. this.edges = new Array();
  68518. this.edgesConnectedCount = 0;
  68519. }
  68520. return FaceAdjacencies;
  68521. }());
  68522. var EdgesRenderer = (function () {
  68523. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  68524. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  68525. if (epsilon === void 0) { epsilon = 0.95; }
  68526. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  68527. this.edgesWidthScalerForOrthographic = 1000.0;
  68528. this.edgesWidthScalerForPerspective = 50.0;
  68529. this._linesPositions = new Array();
  68530. this._linesNormals = new Array();
  68531. this._linesIndices = new Array();
  68532. this._buffers = {};
  68533. this._checkVerticesInsteadOfIndices = false;
  68534. this._source = source;
  68535. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  68536. this._epsilon = epsilon;
  68537. this._prepareRessources();
  68538. this._generateEdgesLines();
  68539. }
  68540. EdgesRenderer.prototype._prepareRessources = function () {
  68541. if (this._lineShader) {
  68542. return;
  68543. }
  68544. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  68545. attributes: ["position", "normal"],
  68546. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  68547. });
  68548. this._lineShader.disableDepthWrite = true;
  68549. this._lineShader.backFaceCulling = false;
  68550. };
  68551. EdgesRenderer.prototype._rebuild = function () {
  68552. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  68553. if (buffer) {
  68554. buffer._rebuild();
  68555. }
  68556. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  68557. if (buffer) {
  68558. buffer._rebuild();
  68559. }
  68560. var scene = this._source.getScene();
  68561. var engine = scene.getEngine();
  68562. this._ib = engine.createIndexBuffer(this._linesIndices);
  68563. };
  68564. EdgesRenderer.prototype.dispose = function () {
  68565. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  68566. if (buffer) {
  68567. buffer.dispose();
  68568. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  68569. }
  68570. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  68571. if (buffer) {
  68572. buffer.dispose();
  68573. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  68574. }
  68575. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  68576. this._lineShader.dispose();
  68577. };
  68578. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  68579. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  68580. return 0;
  68581. }
  68582. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  68583. return 1;
  68584. }
  68585. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  68586. return 2;
  68587. }
  68588. return -1;
  68589. };
  68590. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  68591. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  68592. return 0;
  68593. }
  68594. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  68595. return 1;
  68596. }
  68597. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  68598. return 2;
  68599. }
  68600. return -1;
  68601. };
  68602. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  68603. var needToCreateLine;
  68604. if (edge === undefined) {
  68605. needToCreateLine = true;
  68606. }
  68607. else {
  68608. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  68609. needToCreateLine = dotProduct < this._epsilon;
  68610. }
  68611. if (needToCreateLine) {
  68612. var offset = this._linesPositions.length / 3;
  68613. var normal = p0.subtract(p1);
  68614. normal.normalize();
  68615. // Positions
  68616. this._linesPositions.push(p0.x);
  68617. this._linesPositions.push(p0.y);
  68618. this._linesPositions.push(p0.z);
  68619. this._linesPositions.push(p0.x);
  68620. this._linesPositions.push(p0.y);
  68621. this._linesPositions.push(p0.z);
  68622. this._linesPositions.push(p1.x);
  68623. this._linesPositions.push(p1.y);
  68624. this._linesPositions.push(p1.z);
  68625. this._linesPositions.push(p1.x);
  68626. this._linesPositions.push(p1.y);
  68627. this._linesPositions.push(p1.z);
  68628. // Normals
  68629. this._linesNormals.push(p1.x);
  68630. this._linesNormals.push(p1.y);
  68631. this._linesNormals.push(p1.z);
  68632. this._linesNormals.push(-1);
  68633. this._linesNormals.push(p1.x);
  68634. this._linesNormals.push(p1.y);
  68635. this._linesNormals.push(p1.z);
  68636. this._linesNormals.push(1);
  68637. this._linesNormals.push(p0.x);
  68638. this._linesNormals.push(p0.y);
  68639. this._linesNormals.push(p0.z);
  68640. this._linesNormals.push(-1);
  68641. this._linesNormals.push(p0.x);
  68642. this._linesNormals.push(p0.y);
  68643. this._linesNormals.push(p0.z);
  68644. this._linesNormals.push(1);
  68645. // Indices
  68646. this._linesIndices.push(offset);
  68647. this._linesIndices.push(offset + 1);
  68648. this._linesIndices.push(offset + 2);
  68649. this._linesIndices.push(offset);
  68650. this._linesIndices.push(offset + 2);
  68651. this._linesIndices.push(offset + 3);
  68652. }
  68653. };
  68654. EdgesRenderer.prototype._generateEdgesLines = function () {
  68655. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68656. var indices = this._source.getIndices();
  68657. // First let's find adjacencies
  68658. var adjacencies = new Array();
  68659. var faceNormals = new Array();
  68660. var index;
  68661. var faceAdjacencies;
  68662. // Prepare faces
  68663. for (index = 0; index < indices.length; index += 3) {
  68664. faceAdjacencies = new FaceAdjacencies();
  68665. var p0Index = indices[index];
  68666. var p1Index = indices[index + 1];
  68667. var p2Index = indices[index + 2];
  68668. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  68669. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  68670. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  68671. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  68672. faceNormal.normalize();
  68673. faceNormals.push(faceNormal);
  68674. adjacencies.push(faceAdjacencies);
  68675. }
  68676. // Scan
  68677. for (index = 0; index < adjacencies.length; index++) {
  68678. faceAdjacencies = adjacencies[index];
  68679. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  68680. var otherFaceAdjacencies = adjacencies[otherIndex];
  68681. if (faceAdjacencies.edgesConnectedCount === 3) {
  68682. break;
  68683. }
  68684. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  68685. continue;
  68686. }
  68687. var otherP0 = indices[otherIndex * 3];
  68688. var otherP1 = indices[otherIndex * 3 + 1];
  68689. var otherP2 = indices[otherIndex * 3 + 2];
  68690. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  68691. var otherEdgeIndex;
  68692. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  68693. continue;
  68694. }
  68695. switch (edgeIndex) {
  68696. case 0:
  68697. if (this._checkVerticesInsteadOfIndices) {
  68698. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68699. }
  68700. else {
  68701. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  68702. }
  68703. break;
  68704. case 1:
  68705. if (this._checkVerticesInsteadOfIndices) {
  68706. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68707. }
  68708. else {
  68709. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  68710. }
  68711. break;
  68712. case 2:
  68713. if (this._checkVerticesInsteadOfIndices) {
  68714. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68715. }
  68716. else {
  68717. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  68718. }
  68719. break;
  68720. }
  68721. if (otherEdgeIndex === -1) {
  68722. continue;
  68723. }
  68724. faceAdjacencies.edges[edgeIndex] = otherIndex;
  68725. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  68726. faceAdjacencies.edgesConnectedCount++;
  68727. otherFaceAdjacencies.edgesConnectedCount++;
  68728. if (faceAdjacencies.edgesConnectedCount === 3) {
  68729. break;
  68730. }
  68731. }
  68732. }
  68733. }
  68734. // Create lines
  68735. for (index = 0; index < adjacencies.length; index++) {
  68736. // 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
  68737. var current = adjacencies[index];
  68738. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  68739. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  68740. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  68741. }
  68742. // Merge into a single mesh
  68743. var engine = this._source.getScene().getEngine();
  68744. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  68745. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  68746. this._ib = engine.createIndexBuffer(this._linesIndices);
  68747. this._indicesCount = this._linesIndices.length;
  68748. };
  68749. EdgesRenderer.prototype.render = function () {
  68750. if (!this._lineShader.isReady()) {
  68751. return;
  68752. }
  68753. var scene = this._source.getScene();
  68754. var engine = scene.getEngine();
  68755. this._lineShader._preBind();
  68756. // VBOs
  68757. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  68758. scene.resetCachedMaterial();
  68759. this._lineShader.setColor4("color", this._source.edgesColor);
  68760. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  68761. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  68762. }
  68763. else {
  68764. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  68765. }
  68766. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  68767. this._lineShader.bind(this._source.getWorldMatrix());
  68768. // Draw order
  68769. engine.draw(true, 0, this._indicesCount);
  68770. this._lineShader.unbind();
  68771. engine.setDepthWrite(true);
  68772. };
  68773. return EdgesRenderer;
  68774. }());
  68775. BABYLON.EdgesRenderer = EdgesRenderer;
  68776. })(BABYLON || (BABYLON = {}));
  68777. //# sourceMappingURL=babylon.edgesRenderer.js.map
  68778. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  68779. /// <reference path="..\Math\babylon.math.ts" />
  68780. var BABYLON;
  68781. (function (BABYLON) {
  68782. /**
  68783. * Special Glow Blur post process only blurring the alpha channel
  68784. * It enforces keeping the most luminous color in the color channel.
  68785. */
  68786. var GlowBlurPostProcess = (function (_super) {
  68787. __extends(GlowBlurPostProcess, _super);
  68788. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  68789. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68790. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  68791. _this.direction = direction;
  68792. _this.kernel = kernel;
  68793. _this.onApplyObservable.add(function (effect) {
  68794. effect.setFloat2("screenSize", _this.width, _this.height);
  68795. effect.setVector2("direction", _this.direction);
  68796. effect.setFloat("blurWidth", _this.kernel);
  68797. });
  68798. return _this;
  68799. }
  68800. return GlowBlurPostProcess;
  68801. }(BABYLON.PostProcess));
  68802. /**
  68803. * The highlight layer Helps adding a glow effect around a mesh.
  68804. *
  68805. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  68806. * glowy meshes to your scene.
  68807. *
  68808. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  68809. */
  68810. var HighlightLayer = (function () {
  68811. /**
  68812. * Instantiates a new highlight Layer and references it to the scene..
  68813. * @param name The name of the layer
  68814. * @param scene The scene to use the layer in
  68815. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  68816. */
  68817. function HighlightLayer(name, scene, options) {
  68818. this.name = name;
  68819. this._vertexBuffers = {};
  68820. this._mainTextureDesiredSize = { width: 0, height: 0 };
  68821. this._meshes = {};
  68822. this._maxSize = 0;
  68823. this._shouldRender = false;
  68824. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  68825. this._excludedMeshes = {};
  68826. /**
  68827. * Specifies whether or not the inner glow is ACTIVE in the layer.
  68828. */
  68829. this.innerGlow = true;
  68830. /**
  68831. * Specifies whether or not the outer glow is ACTIVE in the layer.
  68832. */
  68833. this.outerGlow = true;
  68834. /**
  68835. * Specifies wether the highlight layer is enabled or not.
  68836. */
  68837. this.isEnabled = true;
  68838. /**
  68839. * An event triggered when the highlight layer has been disposed.
  68840. * @type {BABYLON.Observable}
  68841. */
  68842. this.onDisposeObservable = new BABYLON.Observable();
  68843. /**
  68844. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  68845. * @type {BABYLON.Observable}
  68846. */
  68847. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  68848. /**
  68849. * An event triggered when the highlight layer is being blurred.
  68850. * @type {BABYLON.Observable}
  68851. */
  68852. this.onBeforeBlurObservable = new BABYLON.Observable();
  68853. /**
  68854. * An event triggered when the highlight layer has been blurred.
  68855. * @type {BABYLON.Observable}
  68856. */
  68857. this.onAfterBlurObservable = new BABYLON.Observable();
  68858. /**
  68859. * An event triggered when the glowing blurred texture is being merged in the scene.
  68860. * @type {BABYLON.Observable}
  68861. */
  68862. this.onBeforeComposeObservable = new BABYLON.Observable();
  68863. /**
  68864. * An event triggered when the glowing blurred texture has been merged in the scene.
  68865. * @type {BABYLON.Observable}
  68866. */
  68867. this.onAfterComposeObservable = new BABYLON.Observable();
  68868. /**
  68869. * An event triggered when the highlight layer changes its size.
  68870. * @type {BABYLON.Observable}
  68871. */
  68872. this.onSizeChangedObservable = new BABYLON.Observable();
  68873. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68874. var engine = scene.getEngine();
  68875. this._engine = engine;
  68876. this._maxSize = this._engine.getCaps().maxTextureSize;
  68877. this._scene.highlightLayers.push(this);
  68878. // Warn on stencil.
  68879. if (!this._engine.isStencilEnable) {
  68880. 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 }");
  68881. }
  68882. // Adapt options
  68883. this._options = options || {
  68884. mainTextureRatio: 0.5,
  68885. blurTextureSizeRatio: 0.5,
  68886. blurHorizontalSize: 1.0,
  68887. blurVerticalSize: 1.0,
  68888. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  68889. };
  68890. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  68891. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  68892. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  68893. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  68894. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  68895. // VBO
  68896. var vertices = [];
  68897. vertices.push(1, 1);
  68898. vertices.push(-1, 1);
  68899. vertices.push(-1, -1);
  68900. vertices.push(1, -1);
  68901. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68902. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  68903. this._createIndexBuffer();
  68904. // Effect
  68905. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  68906. // Render target
  68907. this.setMainTextureSize();
  68908. // Create Textures and post processes
  68909. this.createTextureAndPostProcesses();
  68910. }
  68911. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  68912. /**
  68913. * Gets the horizontal size of the blur.
  68914. */
  68915. get: function () {
  68916. return this._horizontalBlurPostprocess.kernel;
  68917. },
  68918. /**
  68919. * Specifies the horizontal size of the blur.
  68920. */
  68921. set: function (value) {
  68922. this._horizontalBlurPostprocess.kernel = value;
  68923. },
  68924. enumerable: true,
  68925. configurable: true
  68926. });
  68927. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  68928. /**
  68929. * Gets the vertical size of the blur.
  68930. */
  68931. get: function () {
  68932. return this._verticalBlurPostprocess.kernel;
  68933. },
  68934. /**
  68935. * Specifies the vertical size of the blur.
  68936. */
  68937. set: function (value) {
  68938. this._verticalBlurPostprocess.kernel = value;
  68939. },
  68940. enumerable: true,
  68941. configurable: true
  68942. });
  68943. Object.defineProperty(HighlightLayer.prototype, "camera", {
  68944. /**
  68945. * Gets the camera attached to the layer.
  68946. */
  68947. get: function () {
  68948. return this._options.camera;
  68949. },
  68950. enumerable: true,
  68951. configurable: true
  68952. });
  68953. HighlightLayer.prototype._createIndexBuffer = function () {
  68954. var engine = this._scene.getEngine();
  68955. // Indices
  68956. var indices = [];
  68957. indices.push(0);
  68958. indices.push(1);
  68959. indices.push(2);
  68960. indices.push(0);
  68961. indices.push(2);
  68962. indices.push(3);
  68963. this._indexBuffer = engine.createIndexBuffer(indices);
  68964. };
  68965. HighlightLayer.prototype._rebuild = function () {
  68966. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  68967. this._createIndexBuffer();
  68968. };
  68969. /**
  68970. * Creates the render target textures and post processes used in the highlight layer.
  68971. */
  68972. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  68973. var _this = this;
  68974. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  68975. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  68976. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  68977. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  68978. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  68979. width: this._mainTextureDesiredSize.width,
  68980. height: this._mainTextureDesiredSize.height
  68981. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68982. this._mainTexture.activeCamera = this._options.camera;
  68983. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68984. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68985. this._mainTexture.anisotropicFilteringLevel = 1;
  68986. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68987. this._mainTexture.renderParticles = false;
  68988. this._mainTexture.renderList = null;
  68989. this._mainTexture.ignoreCameraViewport = true;
  68990. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  68991. width: blurTextureWidth,
  68992. height: blurTextureHeight
  68993. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68994. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68995. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68996. this._blurTexture.anisotropicFilteringLevel = 16;
  68997. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68998. this._blurTexture.renderParticles = false;
  68999. this._blurTexture.ignoreCameraViewport = true;
  69000. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69001. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  69002. effect.setTexture("textureSampler", _this._mainTexture);
  69003. });
  69004. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  69005. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69006. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  69007. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69008. });
  69009. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69010. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  69011. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69012. });
  69013. }
  69014. else {
  69015. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69016. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  69017. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69018. });
  69019. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69020. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  69021. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69022. });
  69023. }
  69024. this._mainTexture.onAfterUnbindObservable.add(function () {
  69025. _this.onBeforeBlurObservable.notifyObservers(_this);
  69026. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  69027. _this.onAfterBlurObservable.notifyObservers(_this);
  69028. });
  69029. // Custom render function
  69030. var renderSubMesh = function (subMesh) {
  69031. var mesh = subMesh.getRenderingMesh();
  69032. var scene = _this._scene;
  69033. var engine = scene.getEngine();
  69034. // Culling
  69035. engine.setState(subMesh.getMaterial().backFaceCulling);
  69036. // Managing instances
  69037. var batch = mesh._getInstancesRenderList(subMesh._id);
  69038. if (batch.mustReturn) {
  69039. return;
  69040. }
  69041. // Excluded Mesh
  69042. if (_this._excludedMeshes[mesh.uniqueId]) {
  69043. return;
  69044. }
  69045. ;
  69046. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69047. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  69048. var material = subMesh.getMaterial();
  69049. var emissiveTexture = null;
  69050. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  69051. emissiveTexture = material.emissiveTexture;
  69052. }
  69053. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  69054. engine.enableEffect(_this._glowMapGenerationEffect);
  69055. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  69056. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  69057. if (highlightLayerMesh) {
  69058. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  69059. }
  69060. else {
  69061. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  69062. }
  69063. // Alpha test
  69064. if (material && material.needAlphaTesting()) {
  69065. var alphaTexture = material.getAlphaTestTexture();
  69066. if (alphaTexture) {
  69067. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  69068. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69069. }
  69070. }
  69071. // Glow emissive only
  69072. if (emissiveTexture) {
  69073. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  69074. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  69075. }
  69076. // Bones
  69077. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69078. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69079. }
  69080. // Draw
  69081. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  69082. }
  69083. else {
  69084. // Need to reset refresh rate of the shadowMap
  69085. _this._mainTexture.resetRefreshCounter();
  69086. }
  69087. };
  69088. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69089. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  69090. var index;
  69091. var engine = _this._scene.getEngine();
  69092. if (depthOnlySubMeshes.length) {
  69093. engine.setColorWrite(false);
  69094. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69095. renderSubMesh(depthOnlySubMeshes.data[index]);
  69096. }
  69097. engine.setColorWrite(true);
  69098. }
  69099. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69100. renderSubMesh(opaqueSubMeshes.data[index]);
  69101. }
  69102. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69103. renderSubMesh(alphaTestSubMeshes.data[index]);
  69104. }
  69105. for (index = 0; index < transparentSubMeshes.length; index++) {
  69106. renderSubMesh(transparentSubMeshes.data[index]);
  69107. }
  69108. };
  69109. this._mainTexture.onClearObservable.add(function (engine) {
  69110. engine.clear(HighlightLayer.neutralColor, true, true, true);
  69111. });
  69112. };
  69113. /**
  69114. * Checks for the readiness of the element composing the layer.
  69115. * @param subMesh the mesh to check for
  69116. * @param useInstances specify wether or not to use instances to render the mesh
  69117. * @param emissiveTexture the associated emissive texture used to generate the glow
  69118. * @return true if ready otherwise, false
  69119. */
  69120. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  69121. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  69122. return false;
  69123. }
  69124. var defines = [];
  69125. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69126. var mesh = subMesh.getMesh();
  69127. var material = subMesh.getMaterial();
  69128. var uv1 = false;
  69129. var uv2 = false;
  69130. // Alpha test
  69131. if (material && material.needAlphaTesting()) {
  69132. var alphaTexture = material.getAlphaTestTexture();
  69133. if (alphaTexture) {
  69134. defines.push("#define ALPHATEST");
  69135. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  69136. alphaTexture.coordinatesIndex === 1) {
  69137. defines.push("#define DIFFUSEUV2");
  69138. uv2 = true;
  69139. }
  69140. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69141. defines.push("#define DIFFUSEUV1");
  69142. uv1 = true;
  69143. }
  69144. }
  69145. }
  69146. // Emissive
  69147. if (emissiveTexture) {
  69148. defines.push("#define EMISSIVE");
  69149. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  69150. emissiveTexture.coordinatesIndex === 1) {
  69151. defines.push("#define EMISSIVEUV2");
  69152. uv2 = true;
  69153. }
  69154. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69155. defines.push("#define EMISSIVEUV1");
  69156. uv1 = true;
  69157. }
  69158. }
  69159. if (uv1) {
  69160. attribs.push(BABYLON.VertexBuffer.UVKind);
  69161. defines.push("#define UV1");
  69162. }
  69163. if (uv2) {
  69164. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69165. defines.push("#define UV2");
  69166. }
  69167. // Bones
  69168. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69169. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69170. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69171. if (mesh.numBoneInfluencers > 4) {
  69172. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69173. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69174. }
  69175. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69176. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69177. }
  69178. else {
  69179. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69180. }
  69181. // Instances
  69182. if (useInstances) {
  69183. defines.push("#define INSTANCES");
  69184. attribs.push("world0");
  69185. attribs.push("world1");
  69186. attribs.push("world2");
  69187. attribs.push("world3");
  69188. }
  69189. // Get correct effect
  69190. var join = defines.join("\n");
  69191. if (this._cachedDefines !== join) {
  69192. this._cachedDefines = join;
  69193. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  69194. }
  69195. return this._glowMapGenerationEffect.isReady();
  69196. };
  69197. /**
  69198. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  69199. */
  69200. HighlightLayer.prototype.render = function () {
  69201. var currentEffect = this._glowMapMergeEffect;
  69202. // Check
  69203. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  69204. return;
  69205. var engine = this._scene.getEngine();
  69206. this.onBeforeComposeObservable.notifyObservers(this);
  69207. // Render
  69208. engine.enableEffect(currentEffect);
  69209. engine.setState(false);
  69210. // Cache
  69211. var previousStencilBuffer = engine.getStencilBuffer();
  69212. var previousStencilFunction = engine.getStencilFunction();
  69213. var previousStencilMask = engine.getStencilMask();
  69214. var previousStencilOperationPass = engine.getStencilOperationPass();
  69215. var previousStencilOperationFail = engine.getStencilOperationFail();
  69216. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  69217. var previousAlphaMode = engine.getAlphaMode();
  69218. // Texture
  69219. currentEffect.setTexture("textureSampler", this._blurTexture);
  69220. // VBOs
  69221. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  69222. // Stencil operations
  69223. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  69224. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  69225. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  69226. // Draw order
  69227. engine.setAlphaMode(this._options.alphaBlendingMode);
  69228. engine.setStencilMask(0x00);
  69229. engine.setStencilBuffer(true);
  69230. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  69231. if (this.outerGlow) {
  69232. currentEffect.setFloat("offset", 0);
  69233. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  69234. engine.draw(true, 0, 6);
  69235. }
  69236. if (this.innerGlow) {
  69237. currentEffect.setFloat("offset", 1);
  69238. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  69239. engine.draw(true, 0, 6);
  69240. }
  69241. // Restore Cache
  69242. engine.setStencilFunction(previousStencilFunction);
  69243. engine.setStencilMask(previousStencilMask);
  69244. engine.setAlphaMode(previousAlphaMode);
  69245. engine.setStencilBuffer(previousStencilBuffer);
  69246. engine.setStencilOperationPass(previousStencilOperationPass);
  69247. engine.setStencilOperationFail(previousStencilOperationFail);
  69248. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  69249. engine._stencilState.reset();
  69250. this.onAfterComposeObservable.notifyObservers(this);
  69251. // Handle size changes.
  69252. var size = this._mainTexture.getSize();
  69253. this.setMainTextureSize();
  69254. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  69255. // Recreate RTT and post processes on size change.
  69256. this.onSizeChangedObservable.notifyObservers(this);
  69257. this.disposeTextureAndPostProcesses();
  69258. this.createTextureAndPostProcesses();
  69259. }
  69260. };
  69261. /**
  69262. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  69263. * @param mesh The mesh to exclude from the highlight layer
  69264. */
  69265. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  69266. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  69267. if (!meshExcluded) {
  69268. this._excludedMeshes[mesh.uniqueId] = {
  69269. mesh: mesh,
  69270. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  69271. mesh.getEngine().setStencilBuffer(false);
  69272. }),
  69273. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  69274. mesh.getEngine().setStencilBuffer(true);
  69275. }),
  69276. };
  69277. }
  69278. };
  69279. /**
  69280. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  69281. * @param mesh The mesh to highlight
  69282. */
  69283. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  69284. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  69285. if (meshExcluded) {
  69286. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  69287. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  69288. }
  69289. this._excludedMeshes[mesh.uniqueId] = undefined;
  69290. };
  69291. /**
  69292. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  69293. * @param mesh The mesh to highlight
  69294. * @param color The color of the highlight
  69295. * @param glowEmissiveOnly Extract the glow from the emissive texture
  69296. */
  69297. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  69298. var _this = this;
  69299. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  69300. var meshHighlight = this._meshes[mesh.uniqueId];
  69301. if (meshHighlight) {
  69302. meshHighlight.color = color;
  69303. }
  69304. else {
  69305. this._meshes[mesh.uniqueId] = {
  69306. mesh: mesh,
  69307. color: color,
  69308. // Lambda required for capture due to Observable this context
  69309. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  69310. if (_this._excludedMeshes[mesh.uniqueId]) {
  69311. _this.defaultStencilReference(mesh);
  69312. }
  69313. else {
  69314. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  69315. }
  69316. }),
  69317. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  69318. glowEmissiveOnly: glowEmissiveOnly
  69319. };
  69320. }
  69321. this._shouldRender = true;
  69322. };
  69323. /**
  69324. * Remove a mesh from the highlight layer in order to make it stop glowing.
  69325. * @param mesh The mesh to highlight
  69326. */
  69327. HighlightLayer.prototype.removeMesh = function (mesh) {
  69328. var meshHighlight = this._meshes[mesh.uniqueId];
  69329. if (meshHighlight) {
  69330. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  69331. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  69332. }
  69333. this._meshes[mesh.uniqueId] = undefined;
  69334. this._shouldRender = false;
  69335. for (var meshHighlightToCheck in this._meshes) {
  69336. if (meshHighlightToCheck) {
  69337. this._shouldRender = true;
  69338. break;
  69339. }
  69340. }
  69341. };
  69342. /**
  69343. * Returns true if the layer contains information to display, otherwise false.
  69344. */
  69345. HighlightLayer.prototype.shouldRender = function () {
  69346. return this.isEnabled && this._shouldRender;
  69347. };
  69348. /**
  69349. * Sets the main texture desired size which is the closest power of two
  69350. * of the engine canvas size.
  69351. */
  69352. HighlightLayer.prototype.setMainTextureSize = function () {
  69353. if (this._options.mainTextureFixedSize) {
  69354. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  69355. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  69356. }
  69357. else {
  69358. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  69359. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  69360. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  69361. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  69362. }
  69363. };
  69364. /**
  69365. * Force the stencil to the normal expected value for none glowing parts
  69366. */
  69367. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  69368. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  69369. };
  69370. /**
  69371. * Dispose only the render target textures and post process.
  69372. */
  69373. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  69374. this._blurTexture.dispose();
  69375. this._mainTexture.dispose();
  69376. this._downSamplePostprocess.dispose();
  69377. this._horizontalBlurPostprocess.dispose();
  69378. this._verticalBlurPostprocess.dispose();
  69379. };
  69380. /**
  69381. * Dispose the highlight layer and free resources.
  69382. */
  69383. HighlightLayer.prototype.dispose = function () {
  69384. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69385. if (vertexBuffer) {
  69386. vertexBuffer.dispose();
  69387. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69388. }
  69389. if (this._indexBuffer) {
  69390. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69391. this._indexBuffer = null;
  69392. }
  69393. // Clean textures and post processes
  69394. this.disposeTextureAndPostProcesses();
  69395. // Clean mesh references
  69396. for (var id in this._meshes) {
  69397. var meshHighlight = this._meshes[id];
  69398. if (meshHighlight && meshHighlight.mesh) {
  69399. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  69400. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  69401. }
  69402. }
  69403. this._meshes = null;
  69404. for (var id in this._excludedMeshes) {
  69405. var meshHighlight = this._excludedMeshes[id];
  69406. if (meshHighlight) {
  69407. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  69408. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  69409. }
  69410. }
  69411. this._excludedMeshes = null;
  69412. // Remove from scene
  69413. var index = this._scene.highlightLayers.indexOf(this, 0);
  69414. if (index > -1) {
  69415. this._scene.highlightLayers.splice(index, 1);
  69416. }
  69417. // Callback
  69418. this.onDisposeObservable.notifyObservers(this);
  69419. this.onDisposeObservable.clear();
  69420. this.onBeforeRenderMainTextureObservable.clear();
  69421. this.onBeforeBlurObservable.clear();
  69422. this.onBeforeComposeObservable.clear();
  69423. this.onAfterComposeObservable.clear();
  69424. this.onSizeChangedObservable.clear();
  69425. };
  69426. /**
  69427. * The neutral color used during the preparation of the glow effect.
  69428. * This is black by default as the blend operation is a blend operation.
  69429. */
  69430. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  69431. /**
  69432. * Stencil value used for glowing meshes.
  69433. */
  69434. HighlightLayer.glowingMeshStencilReference = 0x02;
  69435. /**
  69436. * Stencil value used for the other meshes in the scene.
  69437. */
  69438. HighlightLayer.normalMeshStencilReference = 0x01;
  69439. return HighlightLayer;
  69440. }());
  69441. BABYLON.HighlightLayer = HighlightLayer;
  69442. })(BABYLON || (BABYLON = {}));
  69443. //# sourceMappingURL=babylon.highlightlayer.js.map
  69444. var BABYLON;
  69445. (function (BABYLON) {
  69446. var MeshAssetTask = (function () {
  69447. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  69448. this.name = name;
  69449. this.meshesNames = meshesNames;
  69450. this.rootUrl = rootUrl;
  69451. this.sceneFilename = sceneFilename;
  69452. this.isCompleted = false;
  69453. }
  69454. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69455. var _this = this;
  69456. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  69457. _this.loadedMeshes = meshes;
  69458. _this.loadedParticleSystems = particleSystems;
  69459. _this.loadedSkeletons = skeletons;
  69460. _this.isCompleted = true;
  69461. if (_this.onSuccess) {
  69462. _this.onSuccess(_this);
  69463. }
  69464. onSuccess();
  69465. }, null, function () {
  69466. if (_this.onError) {
  69467. _this.onError(_this);
  69468. }
  69469. onError();
  69470. });
  69471. };
  69472. return MeshAssetTask;
  69473. }());
  69474. BABYLON.MeshAssetTask = MeshAssetTask;
  69475. var TextFileAssetTask = (function () {
  69476. function TextFileAssetTask(name, url) {
  69477. this.name = name;
  69478. this.url = url;
  69479. this.isCompleted = false;
  69480. }
  69481. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69482. var _this = this;
  69483. BABYLON.Tools.LoadFile(this.url, function (data) {
  69484. _this.text = data;
  69485. _this.isCompleted = true;
  69486. if (_this.onSuccess) {
  69487. _this.onSuccess(_this);
  69488. }
  69489. onSuccess();
  69490. }, null, scene.database, false, function () {
  69491. if (_this.onError) {
  69492. _this.onError(_this);
  69493. }
  69494. onError();
  69495. });
  69496. };
  69497. return TextFileAssetTask;
  69498. }());
  69499. BABYLON.TextFileAssetTask = TextFileAssetTask;
  69500. var BinaryFileAssetTask = (function () {
  69501. function BinaryFileAssetTask(name, url) {
  69502. this.name = name;
  69503. this.url = url;
  69504. this.isCompleted = false;
  69505. }
  69506. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69507. var _this = this;
  69508. BABYLON.Tools.LoadFile(this.url, function (data) {
  69509. _this.data = data;
  69510. _this.isCompleted = true;
  69511. if (_this.onSuccess) {
  69512. _this.onSuccess(_this);
  69513. }
  69514. onSuccess();
  69515. }, null, scene.database, true, function () {
  69516. if (_this.onError) {
  69517. _this.onError(_this);
  69518. }
  69519. onError();
  69520. });
  69521. };
  69522. return BinaryFileAssetTask;
  69523. }());
  69524. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  69525. var ImageAssetTask = (function () {
  69526. function ImageAssetTask(name, url) {
  69527. this.name = name;
  69528. this.url = url;
  69529. this.isCompleted = false;
  69530. }
  69531. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69532. var _this = this;
  69533. var img = new Image();
  69534. BABYLON.Tools.SetCorsBehavior(this.url, img);
  69535. img.onload = function () {
  69536. _this.image = img;
  69537. _this.isCompleted = true;
  69538. if (_this.onSuccess) {
  69539. _this.onSuccess(_this);
  69540. }
  69541. onSuccess();
  69542. };
  69543. img.onerror = function () {
  69544. if (_this.onError) {
  69545. _this.onError(_this);
  69546. }
  69547. onError();
  69548. };
  69549. img.src = this.url;
  69550. };
  69551. return ImageAssetTask;
  69552. }());
  69553. BABYLON.ImageAssetTask = ImageAssetTask;
  69554. var TextureAssetTask = (function () {
  69555. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  69556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69557. this.name = name;
  69558. this.url = url;
  69559. this.noMipmap = noMipmap;
  69560. this.invertY = invertY;
  69561. this.samplingMode = samplingMode;
  69562. this.isCompleted = false;
  69563. }
  69564. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69565. var _this = this;
  69566. var onload = function () {
  69567. _this.isCompleted = true;
  69568. if (_this.onSuccess) {
  69569. _this.onSuccess(_this);
  69570. }
  69571. onSuccess();
  69572. };
  69573. var onerror = function () {
  69574. if (_this.onError) {
  69575. _this.onError(_this);
  69576. }
  69577. onError();
  69578. };
  69579. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  69580. };
  69581. return TextureAssetTask;
  69582. }());
  69583. BABYLON.TextureAssetTask = TextureAssetTask;
  69584. var CubeTextureAssetTask = (function () {
  69585. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  69586. this.name = name;
  69587. this.url = url;
  69588. this.extensions = extensions;
  69589. this.noMipmap = noMipmap;
  69590. this.files = files;
  69591. this.isCompleted = false;
  69592. }
  69593. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69594. var _this = this;
  69595. var onload = function () {
  69596. _this.isCompleted = true;
  69597. if (_this.onSuccess) {
  69598. _this.onSuccess(_this);
  69599. }
  69600. onSuccess();
  69601. };
  69602. var onerror = function () {
  69603. if (_this.onError) {
  69604. _this.onError(_this);
  69605. }
  69606. onError();
  69607. };
  69608. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  69609. };
  69610. return CubeTextureAssetTask;
  69611. }());
  69612. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  69613. var HDRCubeTextureAssetTask = (function () {
  69614. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  69615. if (noMipmap === void 0) { noMipmap = false; }
  69616. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69617. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69618. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69619. this.name = name;
  69620. this.url = url;
  69621. this.size = size;
  69622. this.noMipmap = noMipmap;
  69623. this.generateHarmonics = generateHarmonics;
  69624. this.useInGammaSpace = useInGammaSpace;
  69625. this.usePMREMGenerator = usePMREMGenerator;
  69626. this.isCompleted = false;
  69627. }
  69628. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69629. var _this = this;
  69630. var onload = function () {
  69631. _this.isCompleted = true;
  69632. if (_this.onSuccess) {
  69633. _this.onSuccess(_this);
  69634. }
  69635. onSuccess();
  69636. };
  69637. var onerror = function () {
  69638. if (_this.onError) {
  69639. _this.onError(_this);
  69640. }
  69641. onError();
  69642. };
  69643. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  69644. };
  69645. return HDRCubeTextureAssetTask;
  69646. }());
  69647. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  69648. var AssetsManager = (function () {
  69649. function AssetsManager(scene) {
  69650. this.tasks = new Array();
  69651. this.waitingTasksCount = 0;
  69652. this.useDefaultLoadingScreen = true;
  69653. this._scene = scene;
  69654. }
  69655. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  69656. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  69657. this.tasks.push(task);
  69658. return task;
  69659. };
  69660. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  69661. var task = new TextFileAssetTask(taskName, url);
  69662. this.tasks.push(task);
  69663. return task;
  69664. };
  69665. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  69666. var task = new BinaryFileAssetTask(taskName, url);
  69667. this.tasks.push(task);
  69668. return task;
  69669. };
  69670. AssetsManager.prototype.addImageTask = function (taskName, url) {
  69671. var task = new ImageAssetTask(taskName, url);
  69672. this.tasks.push(task);
  69673. return task;
  69674. };
  69675. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  69676. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69677. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  69678. this.tasks.push(task);
  69679. return task;
  69680. };
  69681. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  69682. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  69683. this.tasks.push(task);
  69684. return task;
  69685. };
  69686. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  69687. if (noMipmap === void 0) { noMipmap = false; }
  69688. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69689. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69690. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69691. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  69692. this.tasks.push(task);
  69693. return task;
  69694. };
  69695. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  69696. this.waitingTasksCount--;
  69697. if (this.waitingTasksCount === 0) {
  69698. if (this.onFinish) {
  69699. this.onFinish(this.tasks);
  69700. }
  69701. this._scene.getEngine().hideLoadingUI();
  69702. }
  69703. };
  69704. AssetsManager.prototype._runTask = function (task) {
  69705. var _this = this;
  69706. task.run(this._scene, function () {
  69707. if (_this.onTaskSuccess) {
  69708. _this.onTaskSuccess(task);
  69709. }
  69710. _this._decreaseWaitingTasksCount();
  69711. }, function () {
  69712. if (_this.onTaskError) {
  69713. _this.onTaskError(task);
  69714. }
  69715. _this._decreaseWaitingTasksCount();
  69716. });
  69717. };
  69718. AssetsManager.prototype.reset = function () {
  69719. this.tasks = new Array();
  69720. return this;
  69721. };
  69722. AssetsManager.prototype.load = function () {
  69723. this.waitingTasksCount = this.tasks.length;
  69724. if (this.waitingTasksCount === 0) {
  69725. if (this.onFinish) {
  69726. this.onFinish(this.tasks);
  69727. }
  69728. return this;
  69729. }
  69730. if (this.useDefaultLoadingScreen) {
  69731. this._scene.getEngine().displayLoadingUI();
  69732. }
  69733. for (var index = 0; index < this.tasks.length; index++) {
  69734. var task = this.tasks[index];
  69735. this._runTask(task);
  69736. }
  69737. return this;
  69738. };
  69739. return AssetsManager;
  69740. }());
  69741. BABYLON.AssetsManager = AssetsManager;
  69742. })(BABYLON || (BABYLON = {}));
  69743. //# sourceMappingURL=babylon.assetsManager.js.map
  69744. var BABYLON;
  69745. (function (BABYLON) {
  69746. var MapTexture = (function (_super) {
  69747. __extends(MapTexture, _super);
  69748. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  69749. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69750. if (useMipMap === void 0) { useMipMap = false; }
  69751. if (margin === void 0) { margin = 0; }
  69752. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  69753. _this.name = name;
  69754. _this._size = size;
  69755. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69756. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69757. // Create the rectPackMap that will allocate portion of the texture
  69758. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  69759. // Create the texture that will store the content
  69760. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  69761. return _this;
  69762. }
  69763. /**
  69764. * Allocate a rectangle of a given size in the texture map
  69765. * @param size the size of the rectangle to allocation
  69766. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  69767. */
  69768. MapTexture.prototype.allocateRect = function (size) {
  69769. return this._rectPackingMap.addRect(size);
  69770. };
  69771. /**
  69772. * Free a given rectangle from the texture map
  69773. * @param rectInfo the instance corresponding to the rect to free.
  69774. */
  69775. MapTexture.prototype.freeRect = function (rectInfo) {
  69776. if (rectInfo) {
  69777. rectInfo.freeContent();
  69778. }
  69779. };
  69780. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  69781. /**
  69782. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  69783. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  69784. * @returns {}
  69785. */
  69786. get: function () {
  69787. return this._rectPackingMap.freeSpace;
  69788. },
  69789. enumerable: true,
  69790. configurable: true
  69791. });
  69792. /**
  69793. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  69794. * 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.
  69795. * Don't forget to call unbindTexture when you're done rendering
  69796. * @param rect the zone to render to
  69797. * @param clear true to clear the portion's color/depth data
  69798. */
  69799. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  69800. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  69801. };
  69802. /**
  69803. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  69804. * 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.
  69805. * Don't forget to call unbindTexture when you're done rendering
  69806. * @param pos the position into the texture
  69807. * @param size the portion to fit the clip space to
  69808. * @param clear true to clear the portion's color/depth data
  69809. */
  69810. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  69811. var engine = this.getScene().getEngine();
  69812. engine.bindFramebuffer(this._texture);
  69813. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  69814. if (clear) {
  69815. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  69816. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  69817. }
  69818. };
  69819. /**
  69820. * Unbind the texture map from the rendering engine.
  69821. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  69822. * @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.
  69823. */
  69824. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  69825. // Dump ?
  69826. if (dumpForDebug) {
  69827. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  69828. }
  69829. var engine = this.getScene().getEngine();
  69830. if (this._replacedViewport) {
  69831. engine.setViewport(this._replacedViewport);
  69832. this._replacedViewport = null;
  69833. }
  69834. engine.unBindFramebuffer(this._texture);
  69835. };
  69836. Object.defineProperty(MapTexture.prototype, "canRescale", {
  69837. get: function () {
  69838. return false;
  69839. },
  69840. enumerable: true,
  69841. configurable: true
  69842. });
  69843. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  69844. // Anyway, there's not much point to use this method for this kind of texture I guess
  69845. MapTexture.prototype.clone = function () {
  69846. return null;
  69847. };
  69848. return MapTexture;
  69849. }(BABYLON.Texture));
  69850. BABYLON.MapTexture = MapTexture;
  69851. })(BABYLON || (BABYLON = {}));
  69852. //# sourceMappingURL=babylon.mapTexture.js.map
  69853. var BABYLON;
  69854. (function (BABYLON) {
  69855. /**
  69856. * This class describe a rectangle that were added to the map.
  69857. * You have access to its coordinates either in pixel or normalized (UV)
  69858. */
  69859. var PackedRect = (function () {
  69860. function PackedRect(root, parent, pos, size) {
  69861. this._pos = pos;
  69862. this._size = size;
  69863. this._root = root;
  69864. this._parent = parent;
  69865. this._contentSize = null;
  69866. this._bottomNode = null;
  69867. this._leftNode = null;
  69868. this._initialSize = null;
  69869. this._rightNode = null;
  69870. }
  69871. Object.defineProperty(PackedRect.prototype, "pos", {
  69872. /**
  69873. * @returns the position of this node into the map
  69874. */
  69875. get: function () {
  69876. return this._pos;
  69877. },
  69878. enumerable: true,
  69879. configurable: true
  69880. });
  69881. Object.defineProperty(PackedRect.prototype, "contentSize", {
  69882. /**
  69883. * @returns the size of the rectangle this node handles
  69884. */
  69885. get: function () {
  69886. return this._contentSize;
  69887. },
  69888. enumerable: true,
  69889. configurable: true
  69890. });
  69891. /**
  69892. * Retrieve the inner position (considering the margin) and stores it into the res object
  69893. * @param res must be a valid Vector2 that will contain the inner position after this call
  69894. */
  69895. PackedRect.prototype.getInnerPosToRef = function (res) {
  69896. var m = this._root._margin;
  69897. res.x = this._pos.x + m;
  69898. res.y = this._pos.y + m;
  69899. };
  69900. /**
  69901. * Retrieve the inner size (considering the margin) and stores it into the res object
  69902. * @param res must be a valid Size that will contain the inner size after this call
  69903. */
  69904. PackedRect.prototype.getInnerSizeToRef = function (res) {
  69905. var m = this._root._margin;
  69906. res.width = this._contentSize.width - (m * 2);
  69907. res.height = this._contentSize.height - (m * 2);
  69908. };
  69909. Object.defineProperty(PackedRect.prototype, "UVs", {
  69910. /**
  69911. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  69912. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  69913. */
  69914. get: function () {
  69915. if (!this._contentSize) {
  69916. throw new Error("Can't compute UVs for this object because it's nor allocated");
  69917. }
  69918. return this.getUVsForCustomSize(this._contentSize);
  69919. },
  69920. enumerable: true,
  69921. configurable: true
  69922. });
  69923. /**
  69924. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  69925. * and then using only a part of the PackRect.
  69926. * This method will return the UVs for this part by given the custom size of what you really use
  69927. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  69928. */
  69929. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  69930. var mainWidth = this._root._size.width;
  69931. var mainHeight = this._root._size.height;
  69932. var margin = this._root._margin;
  69933. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  69934. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  69935. var uvs = new Array();
  69936. uvs.push(topLeft);
  69937. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  69938. uvs.push(rightBottom);
  69939. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  69940. return uvs;
  69941. };
  69942. /**
  69943. * Free this rectangle from the map.
  69944. * Call this method when you no longer need the rectangle to be in the map.
  69945. */
  69946. PackedRect.prototype.freeContent = function () {
  69947. if (!this.contentSize) {
  69948. return;
  69949. }
  69950. this._contentSize = null;
  69951. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  69952. this.attemptDefrag();
  69953. };
  69954. Object.defineProperty(PackedRect.prototype, "isUsed", {
  69955. get: function () {
  69956. return this._contentSize != null || this._leftNode != null;
  69957. },
  69958. enumerable: true,
  69959. configurable: true
  69960. });
  69961. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  69962. var node = this.findNode(contentSize);
  69963. // Not enough space...
  69964. if (!node) {
  69965. return null;
  69966. }
  69967. node.splitNode(contentSize);
  69968. return node;
  69969. };
  69970. PackedRect.prototype.findNode = function (size) {
  69971. var resNode = null;
  69972. var margin = this._root._margin * 2;
  69973. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  69974. if (this.isUsed) {
  69975. if (this._leftNode) {
  69976. resNode = this._leftNode.findNode(size);
  69977. }
  69978. if (!resNode && this._rightNode) {
  69979. resNode = this._rightNode.findNode(size);
  69980. }
  69981. if (!resNode && this._bottomNode) {
  69982. resNode = this._bottomNode.findNode(size);
  69983. }
  69984. }
  69985. else if (this._initialSize) {
  69986. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  69987. resNode = this;
  69988. }
  69989. else {
  69990. return null;
  69991. }
  69992. }
  69993. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  69994. resNode = this;
  69995. }
  69996. return resNode;
  69997. };
  69998. PackedRect.prototype.splitNode = function (contentSize) {
  69999. var cs = PackedRect.TpsSize;
  70000. var margin = this._root._margin * 2;
  70001. cs.copyFrom(contentSize);
  70002. cs.width += margin;
  70003. cs.height += margin;
  70004. // 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)
  70005. if (!this._contentSize && this._initialSize) {
  70006. this._contentSize = cs.clone();
  70007. 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));
  70008. return this._leftNode.splitNode(contentSize);
  70009. }
  70010. else {
  70011. this._contentSize = cs.clone();
  70012. this._initialSize = cs.clone();
  70013. if (cs.width !== this._size.width) {
  70014. 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));
  70015. }
  70016. if (cs.height !== this._size.height) {
  70017. 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));
  70018. }
  70019. return this;
  70020. }
  70021. };
  70022. PackedRect.prototype.attemptDefrag = function () {
  70023. if (!this.isUsed && this.isRecursiveFree) {
  70024. this.clearNode();
  70025. if (this._parent) {
  70026. this._parent.attemptDefrag();
  70027. }
  70028. }
  70029. };
  70030. PackedRect.prototype.clearNode = function () {
  70031. this._initialSize = null;
  70032. this._rightNode = null;
  70033. this._bottomNode = null;
  70034. };
  70035. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  70036. get: function () {
  70037. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  70038. },
  70039. enumerable: true,
  70040. configurable: true
  70041. });
  70042. PackedRect.prototype.evalFreeSize = function (size) {
  70043. var levelSize = 0;
  70044. if (!this.isUsed) {
  70045. var margin = this._root._margin;
  70046. var is = this._initialSize;
  70047. if (is) {
  70048. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  70049. }
  70050. else {
  70051. var size_1 = this._size;
  70052. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  70053. }
  70054. }
  70055. if (this._rightNode) {
  70056. levelSize += this._rightNode.evalFreeSize(0);
  70057. }
  70058. if (this._bottomNode) {
  70059. levelSize += this._bottomNode.evalFreeSize(0);
  70060. }
  70061. return levelSize + size;
  70062. };
  70063. PackedRect.TpsSize = BABYLON.Size.Zero();
  70064. return PackedRect;
  70065. }());
  70066. BABYLON.PackedRect = PackedRect;
  70067. /**
  70068. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  70069. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  70070. * 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.
  70071. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  70072. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  70073. */
  70074. var RectPackingMap = (function (_super) {
  70075. __extends(RectPackingMap, _super);
  70076. /**
  70077. * Create an instance of the object with a dimension using the given size
  70078. * @param size The dimension of the rectangle that will contain all the sub ones.
  70079. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  70080. */
  70081. function RectPackingMap(size, margin) {
  70082. if (margin === void 0) { margin = 0; }
  70083. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  70084. _this._margin = margin;
  70085. _this._root = _this;
  70086. return _this;
  70087. }
  70088. /**
  70089. * Add a rectangle, finding the best location to store it into the map
  70090. * @param size the dimension of the rectangle to store
  70091. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  70092. */
  70093. RectPackingMap.prototype.addRect = function (size) {
  70094. var node = this.findAndSplitNode(size);
  70095. return node;
  70096. };
  70097. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  70098. /**
  70099. * Return the current space free normalized between [0;1]
  70100. * @returns {}
  70101. */
  70102. get: function () {
  70103. var freeSize = 0;
  70104. freeSize = this.evalFreeSize(freeSize);
  70105. return freeSize / (this._size.width * this._size.height);
  70106. },
  70107. enumerable: true,
  70108. configurable: true
  70109. });
  70110. return RectPackingMap;
  70111. }(PackedRect));
  70112. BABYLON.RectPackingMap = RectPackingMap;
  70113. })(BABYLON || (BABYLON = {}));
  70114. //# sourceMappingURL=babylon.rectPackingMap.js.map
  70115. var BABYLON;
  70116. (function (BABYLON) {
  70117. /**
  70118. * This groups together the common properties used for image processing either in direct forward pass
  70119. * or through post processing effect depending on the use of the image processing pipeline in your scene
  70120. * or not.
  70121. */
  70122. var ImageProcessingConfiguration = (function () {
  70123. function ImageProcessingConfiguration() {
  70124. /**
  70125. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  70126. */
  70127. this.colorCurves = new BABYLON.ColorCurves();
  70128. this._colorCurvesEnabled = false;
  70129. this._colorGradingEnabled = false;
  70130. this._colorGradingWithGreenDepth = false;
  70131. this._colorGradingBGR = false;
  70132. this._exposure = 1.0;
  70133. this._toneMappingEnabled = false;
  70134. this._contrast = 1.0;
  70135. /**
  70136. * Vignette stretch size.
  70137. */
  70138. this.vignetteStretch = 0;
  70139. /**
  70140. * Vignette centre X Offset.
  70141. */
  70142. this.vignetteCentreX = 0;
  70143. /**
  70144. * Vignette centre Y Offset.
  70145. */
  70146. this.vignetteCentreY = 0;
  70147. /**
  70148. * Vignette weight or intensity of the vignette effect.
  70149. */
  70150. this.vignetteWeight = 1.5;
  70151. /**
  70152. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70153. * if vignetteEnabled is set to true.
  70154. */
  70155. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  70156. /**
  70157. * Camera field of view used by the Vignette effect.
  70158. */
  70159. this.vignetteCameraFov = 0.5;
  70160. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  70161. this._vignetteEnabled = false;
  70162. this._applyByPostProcess = false;
  70163. /**
  70164. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  70165. * @type {BABYLON.Observable}
  70166. */
  70167. this.onUpdateParameters = new BABYLON.Observable();
  70168. }
  70169. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  70170. /**
  70171. * Gets wether the color curves effect is enabled.
  70172. */
  70173. get: function () {
  70174. return this._colorCurvesEnabled;
  70175. },
  70176. /**
  70177. * Sets wether the color curves effect is enabled.
  70178. */
  70179. set: function (value) {
  70180. if (this._colorCurvesEnabled === value) {
  70181. return;
  70182. }
  70183. this._colorCurvesEnabled = value;
  70184. this._updateParameters();
  70185. },
  70186. enumerable: true,
  70187. configurable: true
  70188. });
  70189. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  70190. /**
  70191. * Gets wether the color grading effect is enabled.
  70192. */
  70193. get: function () {
  70194. return this._colorGradingEnabled;
  70195. },
  70196. /**
  70197. * Sets wether the color grading effect is enabled.
  70198. */
  70199. set: function (value) {
  70200. if (this._colorGradingEnabled === value) {
  70201. return;
  70202. }
  70203. this._colorGradingEnabled = value;
  70204. this._updateParameters();
  70205. },
  70206. enumerable: true,
  70207. configurable: true
  70208. });
  70209. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  70210. /**
  70211. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  70212. */
  70213. get: function () {
  70214. return this._colorGradingWithGreenDepth;
  70215. },
  70216. /**
  70217. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  70218. */
  70219. set: function (value) {
  70220. if (this._colorGradingWithGreenDepth === value) {
  70221. return;
  70222. }
  70223. this._colorGradingWithGreenDepth = value;
  70224. this._updateParameters();
  70225. },
  70226. enumerable: true,
  70227. configurable: true
  70228. });
  70229. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  70230. /**
  70231. * Gets wether the color grading texture contains BGR values.
  70232. */
  70233. get: function () {
  70234. return this._colorGradingBGR;
  70235. },
  70236. /**
  70237. * Sets wether the color grading texture contains BGR values.
  70238. */
  70239. set: function (value) {
  70240. if (this._colorGradingBGR === value) {
  70241. return;
  70242. }
  70243. this._colorGradingBGR = value;
  70244. this._updateParameters();
  70245. },
  70246. enumerable: true,
  70247. configurable: true
  70248. });
  70249. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  70250. /**
  70251. * Gets the Exposure used in the effect.
  70252. */
  70253. get: function () {
  70254. return this._exposure;
  70255. },
  70256. /**
  70257. * Sets the Exposure used in the effect.
  70258. */
  70259. set: function (value) {
  70260. if (this._exposure === value) {
  70261. return;
  70262. }
  70263. this._exposure = value;
  70264. this._updateParameters();
  70265. },
  70266. enumerable: true,
  70267. configurable: true
  70268. });
  70269. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  70270. /**
  70271. * Gets wether the tone mapping effect is enabled.
  70272. */
  70273. get: function () {
  70274. return this._toneMappingEnabled;
  70275. },
  70276. /**
  70277. * Sets wether the tone mapping effect is enabled.
  70278. */
  70279. set: function (value) {
  70280. if (this._toneMappingEnabled === value) {
  70281. return;
  70282. }
  70283. this._toneMappingEnabled = value;
  70284. this._updateParameters();
  70285. },
  70286. enumerable: true,
  70287. configurable: true
  70288. });
  70289. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  70290. /**
  70291. * Gets the contrast used in the effect.
  70292. */
  70293. get: function () {
  70294. return this._contrast;
  70295. },
  70296. /**
  70297. * Sets the contrast used in the effect.
  70298. */
  70299. set: function (value) {
  70300. if (this._contrast === value) {
  70301. return;
  70302. }
  70303. this._contrast = value;
  70304. this._updateParameters();
  70305. },
  70306. enumerable: true,
  70307. configurable: true
  70308. });
  70309. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  70310. /**
  70311. * Gets the vignette blend mode allowing different kind of effect.
  70312. */
  70313. get: function () {
  70314. return this._vignetteBlendMode;
  70315. },
  70316. /**
  70317. * Sets the vignette blend mode allowing different kind of effect.
  70318. */
  70319. set: function (value) {
  70320. if (this._vignetteBlendMode === value) {
  70321. return;
  70322. }
  70323. this._vignetteBlendMode = value;
  70324. this._updateParameters();
  70325. },
  70326. enumerable: true,
  70327. configurable: true
  70328. });
  70329. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  70330. /**
  70331. * Gets wether the vignette effect is enabled.
  70332. */
  70333. get: function () {
  70334. return this._vignetteEnabled;
  70335. },
  70336. /**
  70337. * Sets wether the vignette effect is enabled.
  70338. */
  70339. set: function (value) {
  70340. if (this._vignetteEnabled === value) {
  70341. return;
  70342. }
  70343. this._vignetteEnabled = value;
  70344. this._updateParameters();
  70345. },
  70346. enumerable: true,
  70347. configurable: true
  70348. });
  70349. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  70350. /**
  70351. * Gets wether the image processing is applied through a post process or not.
  70352. */
  70353. get: function () {
  70354. return this._applyByPostProcess;
  70355. },
  70356. /**
  70357. * Sets wether the image processing is applied through a post process or not.
  70358. */
  70359. set: function (value) {
  70360. if (this._applyByPostProcess === value) {
  70361. return;
  70362. }
  70363. this._applyByPostProcess = value;
  70364. this._updateParameters();
  70365. },
  70366. enumerable: true,
  70367. configurable: true
  70368. });
  70369. /**
  70370. * Method called each time the image processing information changes requires to recompile the effect.
  70371. */
  70372. ImageProcessingConfiguration.prototype._updateParameters = function () {
  70373. this.onUpdateParameters.notifyObservers(this);
  70374. };
  70375. ImageProcessingConfiguration.prototype.getClassName = function () {
  70376. return "ImageProcessingConfiguration";
  70377. };
  70378. /**
  70379. * Prepare the list of uniforms associated with the Image Processing effects.
  70380. * @param uniformsList The list of uniforms used in the effect
  70381. * @param defines the list of defines currently in use
  70382. */
  70383. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  70384. if (defines.EXPOSURE) {
  70385. uniforms.push("exposureLinear");
  70386. }
  70387. if (defines.CONTRAST) {
  70388. uniforms.push("contrast");
  70389. }
  70390. if (defines.COLORGRADING) {
  70391. uniforms.push("colorTransformSettings");
  70392. }
  70393. if (defines.VIGNETTE) {
  70394. uniforms.push("vInverseScreenSize");
  70395. uniforms.push("vignetteSettings1");
  70396. uniforms.push("vignetteSettings2");
  70397. }
  70398. if (defines.COLORCURVES) {
  70399. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  70400. }
  70401. };
  70402. /**
  70403. * Prepare the list of samplers associated with the Image Processing effects.
  70404. * @param uniformsList The list of uniforms used in the effect
  70405. * @param defines the list of defines currently in use
  70406. */
  70407. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  70408. if (defines.COLORGRADING) {
  70409. samplersList.push("txColorTransform");
  70410. }
  70411. };
  70412. /**
  70413. * Prepare the list of defines associated to the shader.
  70414. * @param defines the list of defines to complete
  70415. */
  70416. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  70417. defines.VIGNETTE = this.vignetteEnabled;
  70418. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  70419. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  70420. defines.TONEMAPPING = this.toneMappingEnabled;
  70421. defines.CONTRAST = (this.contrast !== 1.0);
  70422. defines.EXPOSURE = (this.exposure !== 1.0);
  70423. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  70424. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  70425. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  70426. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  70427. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  70428. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  70429. };
  70430. /**
  70431. * Returns true if all the image processing information are ready.
  70432. */
  70433. ImageProcessingConfiguration.prototype.isReady = function () {
  70434. // Color Grading texure can not be none blocking.
  70435. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  70436. };
  70437. /**
  70438. * Binds the image processing to the shader.
  70439. * @param effect The effect to bind to
  70440. */
  70441. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  70442. if (aspectRatio === void 0) { aspectRatio = 1; }
  70443. // Color Curves
  70444. if (this._colorCurvesEnabled) {
  70445. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  70446. }
  70447. // Vignette
  70448. if (this._vignetteEnabled) {
  70449. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  70450. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  70451. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  70452. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  70453. var vignetteScaleX = vignetteScaleY * aspectRatio;
  70454. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  70455. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  70456. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  70457. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  70458. var vignettePower = -2.0 * this.vignetteWeight;
  70459. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  70460. }
  70461. // Exposure
  70462. effect.setFloat("exposureLinear", this.exposure);
  70463. // Contrast
  70464. effect.setFloat("contrast", this.contrast);
  70465. // Color transform settings
  70466. if (this.colorGradingTexture) {
  70467. effect.setTexture("txColorTransform", this.colorGradingTexture);
  70468. var textureSize = this.colorGradingTexture.getSize().height;
  70469. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  70470. 0.5 / textureSize, // textureOffset
  70471. textureSize, // textureSize
  70472. this.colorGradingTexture.level // weight
  70473. );
  70474. }
  70475. };
  70476. /**
  70477. * Clones the current image processing instance.
  70478. * @return The cloned image processing
  70479. */
  70480. ImageProcessingConfiguration.prototype.clone = function () {
  70481. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  70482. };
  70483. /**
  70484. * Serializes the current image processing instance to a json representation.
  70485. * @return a JSON representation
  70486. */
  70487. ImageProcessingConfiguration.prototype.serialize = function () {
  70488. return BABYLON.SerializationHelper.Serialize(this);
  70489. };
  70490. /**
  70491. * Parses the image processing from a json representation.
  70492. * @param source the JSON source to parse
  70493. * @return The parsed image processing
  70494. */
  70495. ImageProcessingConfiguration.Parse = function (source) {
  70496. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  70497. };
  70498. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  70499. /**
  70500. * Used to apply the vignette as a mix with the pixel color.
  70501. */
  70502. get: function () {
  70503. return this._VIGNETTEMODE_MULTIPLY;
  70504. },
  70505. enumerable: true,
  70506. configurable: true
  70507. });
  70508. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  70509. /**
  70510. * Used to apply the vignette as a replacement of the pixel color.
  70511. */
  70512. get: function () {
  70513. return this._VIGNETTEMODE_OPAQUE;
  70514. },
  70515. enumerable: true,
  70516. configurable: true
  70517. });
  70518. // Static constants associated to the image processing.
  70519. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  70520. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  70521. __decorate([
  70522. BABYLON.serializeAsColorCurves()
  70523. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  70524. __decorate([
  70525. BABYLON.serialize()
  70526. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  70527. __decorate([
  70528. BABYLON.serializeAsTexture()
  70529. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  70530. __decorate([
  70531. BABYLON.serialize()
  70532. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  70533. __decorate([
  70534. BABYLON.serialize()
  70535. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  70536. __decorate([
  70537. BABYLON.serialize()
  70538. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  70539. __decorate([
  70540. BABYLON.serialize()
  70541. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  70542. __decorate([
  70543. BABYLON.serialize()
  70544. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  70545. __decorate([
  70546. BABYLON.serialize()
  70547. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  70548. __decorate([
  70549. BABYLON.serialize()
  70550. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  70551. __decorate([
  70552. BABYLON.serialize()
  70553. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  70554. __decorate([
  70555. BABYLON.serialize()
  70556. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  70557. __decorate([
  70558. BABYLON.serialize()
  70559. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  70560. __decorate([
  70561. BABYLON.serializeAsColor4()
  70562. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  70563. __decorate([
  70564. BABYLON.serialize()
  70565. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  70566. __decorate([
  70567. BABYLON.serialize()
  70568. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  70569. __decorate([
  70570. BABYLON.serialize()
  70571. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  70572. __decorate([
  70573. BABYLON.serialize()
  70574. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  70575. return ImageProcessingConfiguration;
  70576. }());
  70577. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  70578. })(BABYLON || (BABYLON = {}));
  70579. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  70580. var BABYLON;
  70581. (function (BABYLON) {
  70582. var serializedGeometries = [];
  70583. var serializeGeometry = function (geometry, serializationGeometries) {
  70584. if (serializedGeometries[geometry.id]) {
  70585. return;
  70586. }
  70587. if (geometry.doNotSerialize) {
  70588. return;
  70589. }
  70590. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  70591. serializationGeometries.boxes.push(geometry.serialize());
  70592. }
  70593. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  70594. serializationGeometries.spheres.push(geometry.serialize());
  70595. }
  70596. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  70597. serializationGeometries.cylinders.push(geometry.serialize());
  70598. }
  70599. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  70600. serializationGeometries.toruses.push(geometry.serialize());
  70601. }
  70602. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  70603. serializationGeometries.grounds.push(geometry.serialize());
  70604. }
  70605. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  70606. serializationGeometries.planes.push(geometry.serialize());
  70607. }
  70608. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  70609. serializationGeometries.torusKnots.push(geometry.serialize());
  70610. }
  70611. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  70612. throw new Error("Unknown primitive type");
  70613. }
  70614. else {
  70615. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  70616. }
  70617. serializedGeometries[geometry.id] = true;
  70618. };
  70619. var serializeMesh = function (mesh, serializationScene) {
  70620. var serializationObject = {};
  70621. // Geometry
  70622. var geometry = mesh._geometry;
  70623. if (geometry) {
  70624. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  70625. // 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
  70626. serializeGeometry(geometry, serializationScene.geometries);
  70627. }
  70628. }
  70629. // Custom
  70630. if (mesh.serialize) {
  70631. mesh.serialize(serializationObject);
  70632. }
  70633. return serializationObject;
  70634. };
  70635. var finalizeSingleMesh = function (mesh, serializationObject) {
  70636. //only works if the mesh is already loaded
  70637. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  70638. //serialize material
  70639. if (mesh.material) {
  70640. if (mesh.material instanceof BABYLON.StandardMaterial) {
  70641. serializationObject.materials = serializationObject.materials || [];
  70642. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  70643. serializationObject.materials.push(mesh.material.serialize());
  70644. }
  70645. }
  70646. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  70647. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  70648. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  70649. serializationObject.multiMaterials.push(mesh.material.serialize());
  70650. }
  70651. }
  70652. }
  70653. //serialize geometry
  70654. var geometry = mesh._geometry;
  70655. if (geometry) {
  70656. if (!serializationObject.geometries) {
  70657. serializationObject.geometries = {};
  70658. serializationObject.geometries.boxes = [];
  70659. serializationObject.geometries.spheres = [];
  70660. serializationObject.geometries.cylinders = [];
  70661. serializationObject.geometries.toruses = [];
  70662. serializationObject.geometries.grounds = [];
  70663. serializationObject.geometries.planes = [];
  70664. serializationObject.geometries.torusKnots = [];
  70665. serializationObject.geometries.vertexData = [];
  70666. }
  70667. serializeGeometry(geometry, serializationObject.geometries);
  70668. }
  70669. // Skeletons
  70670. if (mesh.skeleton) {
  70671. serializationObject.skeletons = serializationObject.skeletons || [];
  70672. serializationObject.skeletons.push(mesh.skeleton.serialize());
  70673. }
  70674. //serialize the actual mesh
  70675. serializationObject.meshes = serializationObject.meshes || [];
  70676. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  70677. }
  70678. };
  70679. var SceneSerializer = (function () {
  70680. function SceneSerializer() {
  70681. }
  70682. SceneSerializer.ClearCache = function () {
  70683. serializedGeometries = [];
  70684. };
  70685. SceneSerializer.Serialize = function (scene) {
  70686. var serializationObject = {};
  70687. SceneSerializer.ClearCache();
  70688. // Scene
  70689. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  70690. serializationObject.autoClear = scene.autoClear;
  70691. serializationObject.clearColor = scene.clearColor.asArray();
  70692. serializationObject.ambientColor = scene.ambientColor.asArray();
  70693. serializationObject.gravity = scene.gravity.asArray();
  70694. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  70695. serializationObject.workerCollisions = scene.workerCollisions;
  70696. // Fog
  70697. if (scene.fogMode && scene.fogMode !== 0) {
  70698. serializationObject.fogMode = scene.fogMode;
  70699. serializationObject.fogColor = scene.fogColor.asArray();
  70700. serializationObject.fogStart = scene.fogStart;
  70701. serializationObject.fogEnd = scene.fogEnd;
  70702. serializationObject.fogDensity = scene.fogDensity;
  70703. }
  70704. //Physics
  70705. if (scene.isPhysicsEnabled()) {
  70706. serializationObject.physicsEnabled = true;
  70707. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  70708. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  70709. }
  70710. // Metadata
  70711. if (scene.metadata) {
  70712. serializationObject.metadata = scene.metadata;
  70713. }
  70714. // Morph targets
  70715. serializationObject.morphTargetManagers = [];
  70716. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  70717. var abstractMesh = _a[_i];
  70718. var manager = abstractMesh.morphTargetManager;
  70719. if (manager) {
  70720. serializationObject.morphTargetManagers.push(manager.serialize());
  70721. }
  70722. }
  70723. // Lights
  70724. serializationObject.lights = [];
  70725. var index;
  70726. var light;
  70727. for (index = 0; index < scene.lights.length; index++) {
  70728. light = scene.lights[index];
  70729. if (!light.doNotSerialize) {
  70730. serializationObject.lights.push(light.serialize());
  70731. }
  70732. }
  70733. // Cameras
  70734. serializationObject.cameras = [];
  70735. for (index = 0; index < scene.cameras.length; index++) {
  70736. var camera = scene.cameras[index];
  70737. if (!camera.doNotSerialize) {
  70738. serializationObject.cameras.push(camera.serialize());
  70739. }
  70740. }
  70741. if (scene.activeCamera) {
  70742. serializationObject.activeCameraID = scene.activeCamera.id;
  70743. }
  70744. // Animations
  70745. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  70746. // Materials
  70747. serializationObject.materials = [];
  70748. serializationObject.multiMaterials = [];
  70749. var material;
  70750. for (index = 0; index < scene.materials.length; index++) {
  70751. material = scene.materials[index];
  70752. if (!material.doNotSerialize) {
  70753. serializationObject.materials.push(material.serialize());
  70754. }
  70755. }
  70756. // MultiMaterials
  70757. serializationObject.multiMaterials = [];
  70758. for (index = 0; index < scene.multiMaterials.length; index++) {
  70759. var multiMaterial = scene.multiMaterials[index];
  70760. serializationObject.multiMaterials.push(multiMaterial.serialize());
  70761. }
  70762. // Skeletons
  70763. serializationObject.skeletons = [];
  70764. for (index = 0; index < scene.skeletons.length; index++) {
  70765. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  70766. }
  70767. // Geometries
  70768. serializationObject.geometries = {};
  70769. serializationObject.geometries.boxes = [];
  70770. serializationObject.geometries.spheres = [];
  70771. serializationObject.geometries.cylinders = [];
  70772. serializationObject.geometries.toruses = [];
  70773. serializationObject.geometries.grounds = [];
  70774. serializationObject.geometries.planes = [];
  70775. serializationObject.geometries.torusKnots = [];
  70776. serializationObject.geometries.vertexData = [];
  70777. serializedGeometries = [];
  70778. var geometries = scene.getGeometries();
  70779. for (index = 0; index < geometries.length; index++) {
  70780. var geometry = geometries[index];
  70781. if (geometry.isReady()) {
  70782. serializeGeometry(geometry, serializationObject.geometries);
  70783. }
  70784. }
  70785. // Meshes
  70786. serializationObject.meshes = [];
  70787. for (index = 0; index < scene.meshes.length; index++) {
  70788. var abstractMesh = scene.meshes[index];
  70789. if (abstractMesh instanceof BABYLON.Mesh) {
  70790. var mesh = abstractMesh;
  70791. if (!mesh.doNotSerialize) {
  70792. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  70793. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  70794. }
  70795. }
  70796. }
  70797. }
  70798. // Particles Systems
  70799. serializationObject.particleSystems = [];
  70800. for (index = 0; index < scene.particleSystems.length; index++) {
  70801. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  70802. }
  70803. // Lens flares
  70804. serializationObject.lensFlareSystems = [];
  70805. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  70806. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  70807. }
  70808. // Shadows
  70809. serializationObject.shadowGenerators = [];
  70810. for (index = 0; index < scene.lights.length; index++) {
  70811. light = scene.lights[index];
  70812. var shadowGenerator = light.getShadowGenerator();
  70813. if (shadowGenerator) {
  70814. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  70815. }
  70816. }
  70817. // Action Manager
  70818. if (scene.actionManager) {
  70819. serializationObject.actions = scene.actionManager.serialize("scene");
  70820. }
  70821. // Audio
  70822. serializationObject.sounds = [];
  70823. for (index = 0; index < scene.soundTracks.length; index++) {
  70824. var soundtrack = scene.soundTracks[index];
  70825. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70826. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70827. }
  70828. }
  70829. return serializationObject;
  70830. };
  70831. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  70832. if (withParents === void 0) { withParents = false; }
  70833. if (withChildren === void 0) { withChildren = false; }
  70834. var serializationObject = {};
  70835. SceneSerializer.ClearCache();
  70836. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  70837. if (withParents || withChildren) {
  70838. //deliberate for loop! not for each, appended should be processed as well.
  70839. for (var i = 0; i < toSerialize.length; ++i) {
  70840. if (withChildren) {
  70841. toSerialize[i].getDescendants().forEach(function (node) {
  70842. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  70843. toSerialize.push(node);
  70844. }
  70845. });
  70846. }
  70847. //make sure the array doesn't contain the object already
  70848. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  70849. toSerialize.push(toSerialize[i].parent);
  70850. }
  70851. }
  70852. }
  70853. toSerialize.forEach(function (mesh) {
  70854. finalizeSingleMesh(mesh, serializationObject);
  70855. });
  70856. return serializationObject;
  70857. };
  70858. return SceneSerializer;
  70859. }());
  70860. BABYLON.SceneSerializer = SceneSerializer;
  70861. })(BABYLON || (BABYLON = {}));
  70862. //# sourceMappingURL=babylon.sceneSerializer.js.map
  70863. var BABYLON;
  70864. (function (BABYLON) {
  70865. var ReflectionProbe = (function () {
  70866. function ReflectionProbe(name, size, scene, generateMipMaps) {
  70867. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70868. var _this = this;
  70869. this.name = name;
  70870. this._viewMatrix = BABYLON.Matrix.Identity();
  70871. this._target = BABYLON.Vector3.Zero();
  70872. this._add = BABYLON.Vector3.Zero();
  70873. this.invertYAxis = false;
  70874. this.position = BABYLON.Vector3.Zero();
  70875. this._scene = scene;
  70876. this._scene.reflectionProbes.push(this);
  70877. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  70878. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  70879. switch (faceIndex) {
  70880. case 0:
  70881. _this._add.copyFromFloats(1, 0, 0);
  70882. break;
  70883. case 1:
  70884. _this._add.copyFromFloats(-1, 0, 0);
  70885. break;
  70886. case 2:
  70887. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  70888. break;
  70889. case 3:
  70890. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  70891. break;
  70892. case 4:
  70893. _this._add.copyFromFloats(0, 0, 1);
  70894. break;
  70895. case 5:
  70896. _this._add.copyFromFloats(0, 0, -1);
  70897. break;
  70898. }
  70899. if (_this._attachedMesh) {
  70900. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  70901. }
  70902. _this.position.addToRef(_this._add, _this._target);
  70903. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  70904. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  70905. });
  70906. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  70907. scene.updateTransformMatrix(true);
  70908. });
  70909. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70910. }
  70911. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  70912. get: function () {
  70913. return this._renderTargetTexture.samples;
  70914. },
  70915. set: function (value) {
  70916. this._renderTargetTexture.samples = value;
  70917. },
  70918. enumerable: true,
  70919. configurable: true
  70920. });
  70921. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  70922. get: function () {
  70923. return this._renderTargetTexture.refreshRate;
  70924. },
  70925. set: function (value) {
  70926. this._renderTargetTexture.refreshRate = value;
  70927. },
  70928. enumerable: true,
  70929. configurable: true
  70930. });
  70931. ReflectionProbe.prototype.getScene = function () {
  70932. return this._scene;
  70933. };
  70934. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  70935. get: function () {
  70936. return this._renderTargetTexture;
  70937. },
  70938. enumerable: true,
  70939. configurable: true
  70940. });
  70941. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  70942. get: function () {
  70943. return this._renderTargetTexture.renderList;
  70944. },
  70945. enumerable: true,
  70946. configurable: true
  70947. });
  70948. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  70949. this._attachedMesh = mesh;
  70950. };
  70951. /**
  70952. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70953. *
  70954. * @param renderingGroupId The rendering group id corresponding to its index
  70955. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70956. */
  70957. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70958. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70959. };
  70960. ReflectionProbe.prototype.dispose = function () {
  70961. var index = this._scene.reflectionProbes.indexOf(this);
  70962. if (index !== -1) {
  70963. // Remove from the scene if found
  70964. this._scene.reflectionProbes.splice(index, 1);
  70965. }
  70966. if (this._renderTargetTexture) {
  70967. this._renderTargetTexture.dispose();
  70968. this._renderTargetTexture = null;
  70969. }
  70970. };
  70971. return ReflectionProbe;
  70972. }());
  70973. BABYLON.ReflectionProbe = ReflectionProbe;
  70974. })(BABYLON || (BABYLON = {}));
  70975. //# sourceMappingURL=babylon.reflectionProbe.js.map
  70976. var BABYLON;
  70977. (function (BABYLON) {
  70978. var Layer = (function () {
  70979. function Layer(name, imgUrl, scene, isBackground, color) {
  70980. this.name = name;
  70981. this.scale = new BABYLON.Vector2(1, 1);
  70982. this.offset = new BABYLON.Vector2(0, 0);
  70983. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  70984. this.layerMask = 0x0FFFFFFF;
  70985. this._vertexBuffers = {};
  70986. // Events
  70987. /**
  70988. * An event triggered when the layer is disposed.
  70989. * @type {BABYLON.Observable}
  70990. */
  70991. this.onDisposeObservable = new BABYLON.Observable();
  70992. /**
  70993. * An event triggered before rendering the scene
  70994. * @type {BABYLON.Observable}
  70995. */
  70996. this.onBeforeRenderObservable = new BABYLON.Observable();
  70997. /**
  70998. * An event triggered after rendering the scene
  70999. * @type {BABYLON.Observable}
  71000. */
  71001. this.onAfterRenderObservable = new BABYLON.Observable();
  71002. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  71003. this.isBackground = isBackground === undefined ? true : isBackground;
  71004. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  71005. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71006. this._scene.layers.push(this);
  71007. var engine = this._scene.getEngine();
  71008. // VBO
  71009. var vertices = [];
  71010. vertices.push(1, 1);
  71011. vertices.push(-1, 1);
  71012. vertices.push(-1, -1);
  71013. vertices.push(1, -1);
  71014. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71015. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71016. this._createIndexBuffer();
  71017. // Effects
  71018. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  71019. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  71020. }
  71021. Object.defineProperty(Layer.prototype, "onDispose", {
  71022. set: function (callback) {
  71023. if (this._onDisposeObserver) {
  71024. this.onDisposeObservable.remove(this._onDisposeObserver);
  71025. }
  71026. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  71027. },
  71028. enumerable: true,
  71029. configurable: true
  71030. });
  71031. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  71032. set: function (callback) {
  71033. if (this._onBeforeRenderObserver) {
  71034. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71035. }
  71036. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71037. },
  71038. enumerable: true,
  71039. configurable: true
  71040. });
  71041. Object.defineProperty(Layer.prototype, "onAfterRender", {
  71042. set: function (callback) {
  71043. if (this._onAfterRenderObserver) {
  71044. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71045. }
  71046. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71047. },
  71048. enumerable: true,
  71049. configurable: true
  71050. });
  71051. Layer.prototype._createIndexBuffer = function () {
  71052. var engine = this._scene.getEngine();
  71053. // Indices
  71054. var indices = [];
  71055. indices.push(0);
  71056. indices.push(1);
  71057. indices.push(2);
  71058. indices.push(0);
  71059. indices.push(2);
  71060. indices.push(3);
  71061. this._indexBuffer = engine.createIndexBuffer(indices);
  71062. };
  71063. Layer.prototype._rebuild = function () {
  71064. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  71065. this._createIndexBuffer();
  71066. };
  71067. Layer.prototype.render = function () {
  71068. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  71069. // Check
  71070. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  71071. return;
  71072. var engine = this._scene.getEngine();
  71073. this.onBeforeRenderObservable.notifyObservers(this);
  71074. // Render
  71075. engine.enableEffect(currentEffect);
  71076. engine.setState(false);
  71077. // Texture
  71078. currentEffect.setTexture("textureSampler", this.texture);
  71079. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  71080. // Color
  71081. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  71082. // Scale / offset
  71083. currentEffect.setVector2("offset", this.offset);
  71084. currentEffect.setVector2("scale", this.scale);
  71085. // VBOs
  71086. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  71087. // Draw order
  71088. if (!this.alphaTest) {
  71089. engine.setAlphaMode(this.alphaBlendingMode);
  71090. engine.draw(true, 0, 6);
  71091. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71092. }
  71093. else {
  71094. engine.draw(true, 0, 6);
  71095. }
  71096. this.onAfterRenderObservable.notifyObservers(this);
  71097. };
  71098. Layer.prototype.dispose = function () {
  71099. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71100. if (vertexBuffer) {
  71101. vertexBuffer.dispose();
  71102. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71103. }
  71104. if (this._indexBuffer) {
  71105. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71106. this._indexBuffer = null;
  71107. }
  71108. if (this.texture) {
  71109. this.texture.dispose();
  71110. this.texture = null;
  71111. }
  71112. // Remove from scene
  71113. var index = this._scene.layers.indexOf(this);
  71114. this._scene.layers.splice(index, 1);
  71115. // Callback
  71116. this.onDisposeObservable.notifyObservers(this);
  71117. this.onDisposeObservable.clear();
  71118. this.onAfterRenderObservable.clear();
  71119. this.onBeforeRenderObservable.clear();
  71120. };
  71121. return Layer;
  71122. }());
  71123. BABYLON.Layer = Layer;
  71124. })(BABYLON || (BABYLON = {}));
  71125. //# sourceMappingURL=babylon.layer.js.map
  71126. var BABYLON;
  71127. (function (BABYLON) {
  71128. var TextureTools = (function () {
  71129. function TextureTools() {
  71130. }
  71131. /**
  71132. * Uses the GPU to create a copy texture rescaled at a given size
  71133. * @param texture Texture to copy from
  71134. * @param width Desired width
  71135. * @param height Desired height
  71136. * @return Generated texture
  71137. */
  71138. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  71139. if (useBilinearMode === void 0) { useBilinearMode = true; }
  71140. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  71141. var scene = texture.getScene();
  71142. var engine = scene.getEngine();
  71143. rtt.wrapU = texture.wrapU;
  71144. rtt.wrapV = texture.wrapV;
  71145. rtt.uOffset = texture.uOffset;
  71146. rtt.vOffset = texture.vOffset;
  71147. rtt.uScale = texture.uScale;
  71148. rtt.vScale = texture.vScale;
  71149. rtt.uAng = texture.uAng;
  71150. rtt.vAng = texture.vAng;
  71151. rtt.wAng = texture.wAng;
  71152. rtt.coordinatesIndex = texture.coordinatesIndex;
  71153. rtt.level = texture.level;
  71154. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  71155. rtt._texture.isReady = false;
  71156. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71157. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71158. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71159. passPostProcess.getEffect().executeWhenCompiled(function () {
  71160. passPostProcess.onApply = function (effect) {
  71161. effect.setTexture("textureSampler", texture);
  71162. };
  71163. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  71164. engine.unBindFramebuffer(rtt.getInternalTexture());
  71165. rtt.disposeFramebufferObjects();
  71166. passPostProcess.dispose();
  71167. rtt._texture.isReady = true;
  71168. });
  71169. return rtt;
  71170. };
  71171. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  71172. if (!scene._environmentBRDFTexture) {
  71173. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71174. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71175. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71176. scene._environmentBRDFTexture = texture;
  71177. }
  71178. return scene._environmentBRDFTexture;
  71179. };
  71180. 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=";
  71181. return TextureTools;
  71182. }());
  71183. BABYLON.TextureTools = TextureTools;
  71184. })(BABYLON || (BABYLON = {}));
  71185. //# sourceMappingURL=babylon.textureTools.js.map
  71186. var BABYLON;
  71187. (function (BABYLON) {
  71188. var FramingBehavior = (function () {
  71189. function FramingBehavior() {
  71190. this._mode = FramingBehavior.FitFrustumSidesMode;
  71191. this._radiusScale = 1.0;
  71192. this._positionScale = 0.5;
  71193. this._defaultElevation = 0.3;
  71194. this._elevationReturnTime = 1500;
  71195. this._elevationReturnWaitTime = 1000;
  71196. this._zoomStopsAnimation = false;
  71197. this._framingTime = 1500;
  71198. this._isPointerDown = false;
  71199. this._lastFrameTime = null;
  71200. this._lastInteractionTime = -Infinity;
  71201. // Framing control
  71202. this._animatables = new Array();
  71203. this._betaIsAnimating = false;
  71204. this._lastFrameRadius = 0;
  71205. }
  71206. Object.defineProperty(FramingBehavior.prototype, "name", {
  71207. get: function () {
  71208. return "Framing";
  71209. },
  71210. enumerable: true,
  71211. configurable: true
  71212. });
  71213. Object.defineProperty(FramingBehavior.prototype, "mode", {
  71214. /**
  71215. * Gets current mode used by the behavior.
  71216. */
  71217. get: function () {
  71218. return this._mode;
  71219. },
  71220. /**
  71221. * Sets the current mode used by the behavior
  71222. */
  71223. set: function (mode) {
  71224. this._mode = mode;
  71225. },
  71226. enumerable: true,
  71227. configurable: true
  71228. });
  71229. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  71230. /**
  71231. * Gets the scale applied to the radius
  71232. */
  71233. get: function () {
  71234. return this._radiusScale;
  71235. },
  71236. /**
  71237. * Sets the scale applied to the radius (1 by default)
  71238. */
  71239. set: function (radius) {
  71240. this._radiusScale = radius;
  71241. },
  71242. enumerable: true,
  71243. configurable: true
  71244. });
  71245. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  71246. /**
  71247. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71248. */
  71249. get: function () {
  71250. return this._positionScale;
  71251. },
  71252. /**
  71253. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71254. */
  71255. set: function (scale) {
  71256. this._positionScale = scale;
  71257. },
  71258. enumerable: true,
  71259. configurable: true
  71260. });
  71261. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  71262. /**
  71263. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  71264. * behaviour is triggered, in radians.
  71265. */
  71266. get: function () {
  71267. return this._defaultElevation;
  71268. },
  71269. /**
  71270. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  71271. * behaviour is triggered, in radians.
  71272. */
  71273. set: function (elevation) {
  71274. this._defaultElevation = elevation;
  71275. },
  71276. enumerable: true,
  71277. configurable: true
  71278. });
  71279. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  71280. /**
  71281. * Gets the time (in milliseconds) taken to return to the default beta position.
  71282. * Negative value indicates camera should not return to default.
  71283. */
  71284. get: function () {
  71285. return this._elevationReturnTime;
  71286. },
  71287. /**
  71288. * Sets the time (in milliseconds) taken to return to the default beta position.
  71289. * Negative value indicates camera should not return to default.
  71290. */
  71291. set: function (speed) {
  71292. this._elevationReturnTime = speed;
  71293. },
  71294. enumerable: true,
  71295. configurable: true
  71296. });
  71297. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  71298. /**
  71299. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  71300. */
  71301. get: function () {
  71302. return this._elevationReturnWaitTime;
  71303. },
  71304. /**
  71305. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  71306. */
  71307. set: function (time) {
  71308. this._elevationReturnWaitTime = time;
  71309. },
  71310. enumerable: true,
  71311. configurable: true
  71312. });
  71313. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  71314. /**
  71315. * Gets the flag that indicates if user zooming should stop animation.
  71316. */
  71317. get: function () {
  71318. return this._zoomStopsAnimation;
  71319. },
  71320. /**
  71321. * Sets the flag that indicates if user zooming should stop animation.
  71322. */
  71323. set: function (flag) {
  71324. this._zoomStopsAnimation = flag;
  71325. },
  71326. enumerable: true,
  71327. configurable: true
  71328. });
  71329. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  71330. /**
  71331. * Gets the transition time when framing the mesh, in milliseconds
  71332. */
  71333. get: function () {
  71334. return this._framingTime;
  71335. },
  71336. /**
  71337. * Sets the transition time when framing the mesh, in milliseconds
  71338. */
  71339. set: function (time) {
  71340. this._framingTime = time;
  71341. },
  71342. enumerable: true,
  71343. configurable: true
  71344. });
  71345. FramingBehavior.prototype.attach = function (camera) {
  71346. var _this = this;
  71347. this._attachedCamera = camera;
  71348. var scene = this._attachedCamera.getScene();
  71349. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  71350. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  71351. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71352. _this._isPointerDown = true;
  71353. return;
  71354. }
  71355. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  71356. _this._isPointerDown = false;
  71357. }
  71358. });
  71359. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  71360. if (mesh) {
  71361. _this.zoomOnMesh(mesh);
  71362. }
  71363. });
  71364. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71365. // Stop the animation if there is user interaction and the animation should stop for this interaction
  71366. _this._applyUserInteraction();
  71367. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  71368. // back to the default position after a given timeout
  71369. _this._maintainCameraAboveGround();
  71370. });
  71371. };
  71372. FramingBehavior.prototype.detach = function () {
  71373. var scene = this._attachedCamera.getScene();
  71374. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  71375. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71376. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71377. this._attachedCamera = null;
  71378. };
  71379. /**
  71380. * Targets the given mesh and updates zoom level accordingly.
  71381. * @param mesh The mesh to target.
  71382. * @param radius Optional. If a cached radius position already exists, overrides default.
  71383. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  71384. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  71385. * @param onAnimationEnd Callback triggered at the end of the framing animation
  71386. */
  71387. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  71388. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  71389. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  71390. mesh.computeWorldMatrix(true);
  71391. var boundingBox = mesh.getBoundingInfo().boundingBox;
  71392. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  71393. };
  71394. /**
  71395. * Targets the given mesh and updates zoom level accordingly.
  71396. * @param mesh The mesh to target.
  71397. * @param radius Optional. If a cached radius position already exists, overrides default.
  71398. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  71399. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  71400. * @param onAnimationEnd Callback triggered at the end of the framing animation
  71401. */
  71402. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  71403. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  71404. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  71405. var zoomTarget;
  71406. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  71407. var bottom = minimumWorld.y;
  71408. var top = maximumWorld.y;
  71409. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  71410. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  71411. if (focusOnOriginXZ) {
  71412. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  71413. }
  71414. else {
  71415. var centerWorld = minimumWorld.add(radiusWorld);
  71416. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  71417. }
  71418. if (!this._vectorTransition) {
  71419. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  71420. }
  71421. this._betaIsAnimating = true;
  71422. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  71423. // sets the radius and lower radius bounds
  71424. // Small delta ensures camera is not always at lower zoom limit.
  71425. var delta = 0.1;
  71426. var radius = 0;
  71427. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  71428. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  71429. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  71430. radius = position;
  71431. }
  71432. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  71433. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  71434. if (this._attachedCamera.lowerRadiusLimit === null) {
  71435. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  71436. }
  71437. }
  71438. // transition to new radius
  71439. if (!this._radiusTransition) {
  71440. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  71441. }
  71442. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, onAnimationEnd));
  71443. };
  71444. /**
  71445. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  71446. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  71447. * frustum width.
  71448. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  71449. * to fully enclose the mesh in the viewing frustum.
  71450. */
  71451. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  71452. var size = maximumWorld.subtract(minimumWorld);
  71453. var boxVectorGlobalDiagonal = size.length();
  71454. var frustumSlope = this._getFrustumSlope();
  71455. // Formula for setting distance
  71456. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  71457. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  71458. // Horizon distance
  71459. var radius = radiusWithoutFraming * this._radiusScale;
  71460. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  71461. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  71462. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  71463. var camera = this._attachedCamera;
  71464. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  71465. // Don't exceed the requested limit
  71466. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  71467. }
  71468. // Don't exceed the upper radius limit
  71469. if (camera.upperRadiusLimit) {
  71470. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  71471. }
  71472. return distance;
  71473. };
  71474. /**
  71475. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  71476. * is automatically returned to its default position (expected to be above ground plane).
  71477. */
  71478. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  71479. var _this = this;
  71480. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  71481. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  71482. var limitBeta = Math.PI * 0.5;
  71483. // Bring the camera back up if below the ground plane
  71484. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  71485. this._betaIsAnimating = true;
  71486. //Transition to new position
  71487. this.stopAllAnimations();
  71488. if (!this._betaTransition) {
  71489. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  71490. }
  71491. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  71492. _this._clearAnimationLocks();
  71493. _this.stopAllAnimations();
  71494. }));
  71495. }
  71496. };
  71497. /**
  71498. * Returns the frustum slope based on the canvas ratio and camera FOV
  71499. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  71500. */
  71501. FramingBehavior.prototype._getFrustumSlope = function () {
  71502. // Calculate the viewport ratio
  71503. // Aspect Ratio is Height/Width.
  71504. var camera = this._attachedCamera;
  71505. var engine = camera.getScene().getEngine();
  71506. var aspectRatio = engine.getAspectRatio(camera);
  71507. // Camera FOV is the vertical field of view (top-bottom) in radians.
  71508. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  71509. var frustumSlopeY = Math.tan(camera.fov / 2);
  71510. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  71511. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  71512. // along the forward vector.
  71513. var frustumSlopeX = frustumSlopeY * aspectRatio;
  71514. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  71515. };
  71516. /**
  71517. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  71518. */
  71519. FramingBehavior.prototype._clearAnimationLocks = function () {
  71520. this._betaIsAnimating = false;
  71521. };
  71522. /**
  71523. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  71524. */
  71525. FramingBehavior.prototype._applyUserInteraction = function () {
  71526. if (this.isUserIsMoving) {
  71527. this._lastInteractionTime = BABYLON.Tools.Now;
  71528. this.stopAllAnimations();
  71529. this._clearAnimationLocks();
  71530. }
  71531. };
  71532. /**
  71533. * Stops and removes all animations that have been applied to the camera
  71534. */
  71535. FramingBehavior.prototype.stopAllAnimations = function () {
  71536. this._attachedCamera.animations = [];
  71537. while (this._animatables.length) {
  71538. if (this._animatables[0]) {
  71539. this._animatables[0].onAnimationEnd = null;
  71540. this._animatables[0].stop();
  71541. }
  71542. this._animatables.shift();
  71543. }
  71544. };
  71545. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  71546. /**
  71547. * Gets a value indicating if the user is moving the camera
  71548. */
  71549. get: function () {
  71550. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  71551. this._attachedCamera.inertialBetaOffset !== 0 ||
  71552. this._attachedCamera.inertialRadiusOffset !== 0 ||
  71553. this._attachedCamera.inertialPanningX !== 0 ||
  71554. this._attachedCamera.inertialPanningY !== 0 ||
  71555. this._isPointerDown;
  71556. },
  71557. enumerable: true,
  71558. configurable: true
  71559. });
  71560. /**
  71561. * The easing function used by animations
  71562. */
  71563. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  71564. /**
  71565. * The easing mode used by animations
  71566. */
  71567. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  71568. // Statics
  71569. /**
  71570. * The camera can move all the way towards the mesh.
  71571. */
  71572. FramingBehavior.IgnoreBoundsSizeMode = 0;
  71573. /**
  71574. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  71575. */
  71576. FramingBehavior.FitFrustumSidesMode = 1;
  71577. return FramingBehavior;
  71578. }());
  71579. BABYLON.FramingBehavior = FramingBehavior;
  71580. })(BABYLON || (BABYLON = {}));
  71581. //# sourceMappingURL=babylon.framingBehavior.js.map
  71582. var BABYLON;
  71583. (function (BABYLON) {
  71584. /**
  71585. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  71586. */
  71587. var BouncingBehavior = (function () {
  71588. function BouncingBehavior() {
  71589. /**
  71590. * The duration of the animation, in milliseconds
  71591. */
  71592. this.transitionDuration = 450;
  71593. /**
  71594. * Length of the distance animated by the transition when lower radius is reached
  71595. */
  71596. this.lowerRadiusTransitionRange = 2;
  71597. /**
  71598. * Length of the distance animated by the transition when upper radius is reached
  71599. */
  71600. this.upperRadiusTransitionRange = -2;
  71601. this._autoTransitionRange = false;
  71602. // Animations
  71603. this._radiusIsAnimating = false;
  71604. this._radiusBounceTransition = null;
  71605. this._animatables = new Array();
  71606. }
  71607. Object.defineProperty(BouncingBehavior.prototype, "name", {
  71608. get: function () {
  71609. return "Bouncing";
  71610. },
  71611. enumerable: true,
  71612. configurable: true
  71613. });
  71614. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  71615. /**
  71616. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  71617. */
  71618. get: function () {
  71619. return this._autoTransitionRange;
  71620. },
  71621. /**
  71622. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  71623. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  71624. */
  71625. set: function (value) {
  71626. var _this = this;
  71627. if (this._autoTransitionRange === value) {
  71628. return;
  71629. }
  71630. this._autoTransitionRange = value;
  71631. var camera = this._attachedCamera;
  71632. if (value) {
  71633. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  71634. if (!mesh) {
  71635. return;
  71636. }
  71637. mesh.computeWorldMatrix(true);
  71638. var diagonal = mesh.getBoundingInfo().diagonalLength;
  71639. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  71640. _this.upperRadiusTransitionRange = diagonal * 0.05;
  71641. });
  71642. }
  71643. else if (this._onMeshTargetChangedObserver) {
  71644. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71645. }
  71646. },
  71647. enumerable: true,
  71648. configurable: true
  71649. });
  71650. BouncingBehavior.prototype.attach = function (camera) {
  71651. var _this = this;
  71652. this._attachedCamera = camera;
  71653. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71654. // Add the bounce animation to the lower radius limit
  71655. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  71656. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  71657. }
  71658. // Add the bounce animation to the upper radius limit
  71659. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  71660. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  71661. }
  71662. });
  71663. };
  71664. BouncingBehavior.prototype.detach = function () {
  71665. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71666. if (this._onMeshTargetChangedObserver) {
  71667. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71668. }
  71669. this._attachedCamera = null;
  71670. };
  71671. /**
  71672. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  71673. * @param radiusLimit The limit to check against.
  71674. * @return Bool to indicate if at limit.
  71675. */
  71676. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  71677. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  71678. return true;
  71679. }
  71680. return false;
  71681. };
  71682. /**
  71683. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  71684. * @param radiusDelta The delta by which to animate to. Can be negative.
  71685. */
  71686. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  71687. var _this = this;
  71688. if (!this._radiusBounceTransition) {
  71689. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  71690. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  71691. }
  71692. // Prevent zoom until bounce has completed
  71693. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  71694. this._attachedCamera.wheelPrecision = Infinity;
  71695. this._attachedCamera.inertialRadiusOffset = 0;
  71696. // Animate to the radius limit
  71697. this.stopAllAnimations();
  71698. this._radiusIsAnimating = true;
  71699. 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(); }));
  71700. };
  71701. /**
  71702. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  71703. */
  71704. BouncingBehavior.prototype._clearAnimationLocks = function () {
  71705. this._radiusIsAnimating = false;
  71706. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  71707. };
  71708. /**
  71709. * Stops and removes all animations that have been applied to the camera
  71710. */
  71711. BouncingBehavior.prototype.stopAllAnimations = function () {
  71712. this._attachedCamera.animations = [];
  71713. while (this._animatables.length) {
  71714. this._animatables[0].onAnimationEnd = null;
  71715. this._animatables[0].stop();
  71716. this._animatables.shift();
  71717. }
  71718. };
  71719. /**
  71720. * The easing function used by animations
  71721. */
  71722. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  71723. /**
  71724. * The easing mode used by animations
  71725. */
  71726. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  71727. return BouncingBehavior;
  71728. }());
  71729. BABYLON.BouncingBehavior = BouncingBehavior;
  71730. })(BABYLON || (BABYLON = {}));
  71731. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  71732. var BABYLON;
  71733. (function (BABYLON) {
  71734. var AutoRotationBehavior = (function () {
  71735. function AutoRotationBehavior() {
  71736. this._zoomStopsAnimation = false;
  71737. this._idleRotationSpeed = 0.05;
  71738. this._idleRotationWaitTime = 2000;
  71739. this._idleRotationSpinupTime = 2000;
  71740. this._isPointerDown = false;
  71741. this._lastFrameTime = null;
  71742. this._lastInteractionTime = -Infinity;
  71743. this._cameraRotationSpeed = 0;
  71744. this._lastFrameRadius = 0;
  71745. }
  71746. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  71747. get: function () {
  71748. return "AutoRotation";
  71749. },
  71750. enumerable: true,
  71751. configurable: true
  71752. });
  71753. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  71754. /**
  71755. * Gets the flag that indicates if user zooming should stop animation.
  71756. */
  71757. get: function () {
  71758. return this._zoomStopsAnimation;
  71759. },
  71760. /**
  71761. * Sets the flag that indicates if user zooming should stop animation.
  71762. */
  71763. set: function (flag) {
  71764. this._zoomStopsAnimation = flag;
  71765. },
  71766. enumerable: true,
  71767. configurable: true
  71768. });
  71769. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  71770. /**
  71771. * Gets the default speed at which the camera rotates around the model.
  71772. */
  71773. get: function () {
  71774. return this._idleRotationSpeed;
  71775. },
  71776. /**
  71777. * Sets the default speed at which the camera rotates around the model.
  71778. */
  71779. set: function (speed) {
  71780. this._idleRotationSpeed = speed;
  71781. },
  71782. enumerable: true,
  71783. configurable: true
  71784. });
  71785. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  71786. /**
  71787. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  71788. */
  71789. get: function () {
  71790. return this._idleRotationWaitTime;
  71791. },
  71792. /**
  71793. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  71794. */
  71795. set: function (time) {
  71796. this._idleRotationWaitTime = time;
  71797. },
  71798. enumerable: true,
  71799. configurable: true
  71800. });
  71801. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  71802. /**
  71803. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  71804. */
  71805. get: function () {
  71806. return this._idleRotationSpinupTime;
  71807. },
  71808. /**
  71809. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  71810. */
  71811. set: function (time) {
  71812. this._idleRotationSpinupTime = time;
  71813. },
  71814. enumerable: true,
  71815. configurable: true
  71816. });
  71817. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  71818. /**
  71819. * Gets a value indicating if the camera is currently rotating because of this behavior
  71820. */
  71821. get: function () {
  71822. return Math.abs(this._cameraRotationSpeed) > 0;
  71823. },
  71824. enumerable: true,
  71825. configurable: true
  71826. });
  71827. AutoRotationBehavior.prototype.attach = function (camera) {
  71828. var _this = this;
  71829. this._attachedCamera = camera;
  71830. var scene = this._attachedCamera.getScene();
  71831. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  71832. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71833. _this._isPointerDown = true;
  71834. return;
  71835. }
  71836. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  71837. _this._isPointerDown = false;
  71838. }
  71839. });
  71840. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71841. var now = BABYLON.Tools.Now;
  71842. var dt = 0;
  71843. if (_this._lastFrameTime != null) {
  71844. dt = now - _this._lastFrameTime;
  71845. }
  71846. _this._lastFrameTime = now;
  71847. // Stop the animation if there is user interaction and the animation should stop for this interaction
  71848. _this._applyUserInteraction();
  71849. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  71850. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  71851. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  71852. // Step camera rotation by rotation speed
  71853. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  71854. });
  71855. };
  71856. AutoRotationBehavior.prototype.detach = function () {
  71857. var scene = this._attachedCamera.getScene();
  71858. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  71859. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71860. this._attachedCamera = null;
  71861. };
  71862. /**
  71863. * Returns true if user is scrolling.
  71864. * @return true if user is scrolling.
  71865. */
  71866. AutoRotationBehavior.prototype._userIsZooming = function () {
  71867. return this._attachedCamera.inertialRadiusOffset !== 0;
  71868. };
  71869. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  71870. var zoomHasHitLimit = false;
  71871. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  71872. zoomHasHitLimit = true;
  71873. }
  71874. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  71875. this._lastFrameRadius = this._attachedCamera.radius;
  71876. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  71877. };
  71878. /**
  71879. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  71880. */
  71881. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  71882. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  71883. this._lastInteractionTime = BABYLON.Tools.Now;
  71884. }
  71885. };
  71886. // Tools
  71887. AutoRotationBehavior.prototype._userIsMoving = function () {
  71888. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  71889. this._attachedCamera.inertialBetaOffset !== 0 ||
  71890. this._attachedCamera.inertialRadiusOffset !== 0 ||
  71891. this._attachedCamera.inertialPanningX !== 0 ||
  71892. this._attachedCamera.inertialPanningY !== 0 ||
  71893. this._isPointerDown;
  71894. };
  71895. return AutoRotationBehavior;
  71896. }());
  71897. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  71898. })(BABYLON || (BABYLON = {}));
  71899. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  71900. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nfloat comp=sign(dot(normalW,faceNormal));\nnormalW*=-comp;\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  71901. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec4 vNormalReoderParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vNormalReoderParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap.x=vNormalReoderParams.x+vNormalReoderParams.y*map.x;\nmap.y=vNormalReoderParams.z+vNormalReoderParams.w*map.y;\nmap=map*255./127.-128./127.;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec4 vNormalReoderParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec4 vNormalReoderParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  71902. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  71903. var BABYLON;
  71904. (function (BABYLON) {
  71905. var GridMaterialDefines = (function (_super) {
  71906. __extends(GridMaterialDefines, _super);
  71907. function GridMaterialDefines() {
  71908. var _this = _super.call(this) || this;
  71909. _this.TRANSPARENT = false;
  71910. _this.FOG = false;
  71911. _this.PREMULTIPLYALPHA = false;
  71912. _this.rebuild();
  71913. return _this;
  71914. }
  71915. return GridMaterialDefines;
  71916. }(BABYLON.MaterialDefines));
  71917. /**
  71918. * The grid materials allows you to wrap any shape with a grid.
  71919. * Colors are customizable.
  71920. */
  71921. var GridMaterial = (function (_super) {
  71922. __extends(GridMaterial, _super);
  71923. /**
  71924. * constructor
  71925. * @param name The name given to the material in order to identify it afterwards.
  71926. * @param scene The scene the material is used in.
  71927. */
  71928. function GridMaterial(name, scene) {
  71929. var _this = _super.call(this, name, scene) || this;
  71930. /**
  71931. * Main color of the grid (e.g. between lines)
  71932. */
  71933. _this.mainColor = BABYLON.Color3.Black();
  71934. /**
  71935. * Color of the grid lines.
  71936. */
  71937. _this.lineColor = BABYLON.Color3.Teal();
  71938. /**
  71939. * The scale of the grid compared to unit.
  71940. */
  71941. _this.gridRatio = 1.0;
  71942. /**
  71943. * The frequency of thicker lines.
  71944. */
  71945. _this.majorUnitFrequency = 10;
  71946. /**
  71947. * The visibility of minor units in the grid.
  71948. */
  71949. _this.minorUnitVisibility = 0.33;
  71950. /**
  71951. * The grid opacity outside of the lines.
  71952. */
  71953. _this.opacity = 1.0;
  71954. /**
  71955. * Determine RBG output is premultiplied by alpha value.
  71956. */
  71957. _this.preMultiplyAlpha = false;
  71958. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  71959. return _this;
  71960. }
  71961. /**
  71962. * Returns wehter or not the grid requires alpha blending.
  71963. */
  71964. GridMaterial.prototype.needAlphaBlending = function () {
  71965. return this.opacity < 1.0;
  71966. };
  71967. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71968. if (this.isFrozen) {
  71969. if (this._wasPreviouslyReady && subMesh.effect) {
  71970. return true;
  71971. }
  71972. }
  71973. if (!subMesh._materialDefines) {
  71974. subMesh._materialDefines = new GridMaterialDefines();
  71975. }
  71976. var defines = subMesh._materialDefines;
  71977. var scene = this.getScene();
  71978. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  71979. if (this._renderId === scene.getRenderId()) {
  71980. return true;
  71981. }
  71982. }
  71983. var engine = scene.getEngine();
  71984. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  71985. defines.TRANSPARENT = !defines.TRANSPARENT;
  71986. defines.markAsUnprocessed();
  71987. }
  71988. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  71989. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  71990. defines.markAsUnprocessed();
  71991. }
  71992. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  71993. // Get correct effect
  71994. if (defines.isDirty) {
  71995. defines.markAsProcessed();
  71996. scene.resetCachedMaterial();
  71997. // Attributes
  71998. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71999. // Defines
  72000. var join = defines.toString();
  72001. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  72002. }
  72003. if (!subMesh.effect.isReady()) {
  72004. return false;
  72005. }
  72006. this._renderId = scene.getRenderId();
  72007. this._wasPreviouslyReady = true;
  72008. return true;
  72009. };
  72010. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  72011. var scene = this.getScene();
  72012. var defines = subMesh._materialDefines;
  72013. if (!defines) {
  72014. return;
  72015. }
  72016. var effect = subMesh.effect;
  72017. this._activeEffect = effect;
  72018. // Matrices
  72019. this.bindOnlyWorldMatrix(world);
  72020. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  72021. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  72022. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  72023. // Uniforms
  72024. if (this._mustRebind(scene, effect)) {
  72025. this._activeEffect.setColor3("mainColor", this.mainColor);
  72026. this._activeEffect.setColor3("lineColor", this.lineColor);
  72027. this._gridControl.x = this.gridRatio;
  72028. this._gridControl.y = Math.round(this.majorUnitFrequency);
  72029. this._gridControl.z = this.minorUnitVisibility;
  72030. this._gridControl.w = this.opacity;
  72031. this._activeEffect.setVector4("gridControl", this._gridControl);
  72032. }
  72033. // Fog
  72034. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  72035. this._afterBind(mesh, this._activeEffect);
  72036. };
  72037. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  72038. _super.prototype.dispose.call(this, forceDisposeEffect);
  72039. };
  72040. GridMaterial.prototype.clone = function (name) {
  72041. var _this = this;
  72042. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  72043. };
  72044. GridMaterial.prototype.serialize = function () {
  72045. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72046. serializationObject.customType = "BABYLON.GridMaterial";
  72047. return serializationObject;
  72048. };
  72049. GridMaterial.prototype.getClassName = function () {
  72050. return "GridMaterial";
  72051. };
  72052. GridMaterial.Parse = function (source, scene, rootUrl) {
  72053. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  72054. };
  72055. __decorate([
  72056. BABYLON.serializeAsColor3()
  72057. ], GridMaterial.prototype, "mainColor", void 0);
  72058. __decorate([
  72059. BABYLON.serializeAsColor3()
  72060. ], GridMaterial.prototype, "lineColor", void 0);
  72061. __decorate([
  72062. BABYLON.serialize()
  72063. ], GridMaterial.prototype, "gridRatio", void 0);
  72064. __decorate([
  72065. BABYLON.serialize()
  72066. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  72067. __decorate([
  72068. BABYLON.serialize()
  72069. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  72070. __decorate([
  72071. BABYLON.serialize()
  72072. ], GridMaterial.prototype, "opacity", void 0);
  72073. __decorate([
  72074. BABYLON.serialize()
  72075. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  72076. return GridMaterial;
  72077. }(BABYLON.PushMaterial));
  72078. BABYLON.GridMaterial = GridMaterial;
  72079. })(BABYLON || (BABYLON = {}));
  72080. //# sourceMappingURL=babylon.gridmaterial.js.map
  72081. 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}";
  72082. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=vPosition/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  72083. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72084. var BABYLON;
  72085. (function (BABYLON) {
  72086. var GLTFLoaderCoordinateSystemMode;
  72087. (function (GLTFLoaderCoordinateSystemMode) {
  72088. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  72089. // 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.
  72090. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  72091. // The glTF right-handed data is not transformed in any form and is loaded directly.
  72092. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  72093. // Sets the useRightHandedSystem flag on the scene.
  72094. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  72095. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  72096. var GLTFFileLoader = (function () {
  72097. function GLTFFileLoader() {
  72098. // V2 options
  72099. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  72100. this.name = "gltf";
  72101. this.extensions = {
  72102. ".gltf": { isBinary: false },
  72103. ".glb": { isBinary: true }
  72104. };
  72105. }
  72106. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  72107. var loaderData = GLTFFileLoader._parse(data, onError);
  72108. if (!loaderData) {
  72109. return;
  72110. }
  72111. var loader = this._getLoader(loaderData, onError);
  72112. if (!loader) {
  72113. return;
  72114. }
  72115. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72116. };
  72117. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  72118. var loaderData = GLTFFileLoader._parse(data, onError);
  72119. if (!loaderData) {
  72120. return;
  72121. }
  72122. var loader = this._getLoader(loaderData, onError);
  72123. if (!loader) {
  72124. return;
  72125. }
  72126. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72127. };
  72128. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  72129. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  72130. };
  72131. GLTFFileLoader._parse = function (data, onError) {
  72132. if (data instanceof ArrayBuffer) {
  72133. return GLTFFileLoader._parseBinary(data, onError);
  72134. }
  72135. try {
  72136. return {
  72137. json: JSON.parse(data),
  72138. bin: null
  72139. };
  72140. }
  72141. catch (e) {
  72142. onError(e.message);
  72143. return null;
  72144. }
  72145. };
  72146. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  72147. var loaderVersion = { major: 2, minor: 0 };
  72148. var asset = loaderData.json.asset || {};
  72149. var version = GLTFFileLoader._parseVersion(asset.version);
  72150. if (!version) {
  72151. onError("Invalid version: " + asset.version);
  72152. return null;
  72153. }
  72154. if (asset.minVersion !== undefined) {
  72155. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  72156. if (!minVersion) {
  72157. onError("Invalid minimum version: " + asset.minVersion);
  72158. return null;
  72159. }
  72160. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  72161. onError("Incompatible minimum version: " + asset.minVersion);
  72162. return null;
  72163. }
  72164. }
  72165. var createLoaders = {
  72166. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  72167. 2: GLTFFileLoader.CreateGLTFLoaderV2
  72168. };
  72169. var createLoader = createLoaders[version.major];
  72170. if (!createLoader) {
  72171. onError("Unsupported version: " + asset.version);
  72172. return null;
  72173. }
  72174. return createLoader(this);
  72175. };
  72176. GLTFFileLoader._parseBinary = function (data, onError) {
  72177. var Binary = {
  72178. Magic: 0x46546C67
  72179. };
  72180. var binaryReader = new BinaryReader(data);
  72181. var magic = binaryReader.readUint32();
  72182. if (magic !== Binary.Magic) {
  72183. onError("Unexpected magic: " + magic);
  72184. return null;
  72185. }
  72186. var version = binaryReader.readUint32();
  72187. switch (version) {
  72188. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  72189. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  72190. }
  72191. onError("Unsupported version: " + version);
  72192. return null;
  72193. };
  72194. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  72195. var ContentFormat = {
  72196. JSON: 0
  72197. };
  72198. var length = binaryReader.readUint32();
  72199. if (length != binaryReader.getLength()) {
  72200. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72201. return null;
  72202. }
  72203. var contentLength = binaryReader.readUint32();
  72204. var contentFormat = binaryReader.readUint32();
  72205. var content;
  72206. switch (contentFormat) {
  72207. case ContentFormat.JSON:
  72208. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  72209. break;
  72210. default:
  72211. onError("Unexpected content format: " + contentFormat);
  72212. return null;
  72213. }
  72214. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  72215. var body = binaryReader.readUint8Array(bytesRemaining);
  72216. return {
  72217. json: content,
  72218. bin: body
  72219. };
  72220. };
  72221. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  72222. var ChunkFormat = {
  72223. JSON: 0x4E4F534A,
  72224. BIN: 0x004E4942
  72225. };
  72226. var length = binaryReader.readUint32();
  72227. if (length !== binaryReader.getLength()) {
  72228. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72229. return null;
  72230. }
  72231. // JSON chunk
  72232. var chunkLength = binaryReader.readUint32();
  72233. var chunkFormat = binaryReader.readUint32();
  72234. if (chunkFormat !== ChunkFormat.JSON) {
  72235. onError("First chunk format is not JSON");
  72236. return null;
  72237. }
  72238. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  72239. // Look for BIN chunk
  72240. var bin = null;
  72241. while (binaryReader.getPosition() < binaryReader.getLength()) {
  72242. chunkLength = binaryReader.readUint32();
  72243. chunkFormat = binaryReader.readUint32();
  72244. switch (chunkFormat) {
  72245. case ChunkFormat.JSON:
  72246. onError("Unexpected JSON chunk");
  72247. return null;
  72248. case ChunkFormat.BIN:
  72249. bin = binaryReader.readUint8Array(chunkLength);
  72250. break;
  72251. default:
  72252. // ignore unrecognized chunkFormat
  72253. binaryReader.skipBytes(chunkLength);
  72254. break;
  72255. }
  72256. }
  72257. return {
  72258. json: json,
  72259. bin: bin
  72260. };
  72261. };
  72262. GLTFFileLoader._parseVersion = function (version) {
  72263. if (!version) {
  72264. return null;
  72265. }
  72266. var parts = version.split(".");
  72267. if (parts.length != 2) {
  72268. return null;
  72269. }
  72270. var major = +parts[0];
  72271. if (isNaN(major)) {
  72272. return null;
  72273. }
  72274. var minor = +parts[1];
  72275. if (isNaN(minor)) {
  72276. return null;
  72277. }
  72278. return {
  72279. major: major,
  72280. minor: minor
  72281. };
  72282. };
  72283. GLTFFileLoader._compareVersion = function (a, b) {
  72284. if (a.major > b.major)
  72285. return 1;
  72286. if (a.major < b.major)
  72287. return -1;
  72288. if (a.minor > b.minor)
  72289. return 1;
  72290. if (a.minor < b.minor)
  72291. return -1;
  72292. return 0;
  72293. };
  72294. GLTFFileLoader._decodeBufferToText = function (view) {
  72295. var result = "";
  72296. var length = view.byteLength;
  72297. for (var i = 0; i < length; ++i) {
  72298. result += String.fromCharCode(view[i]);
  72299. }
  72300. return result;
  72301. };
  72302. // V1 options
  72303. GLTFFileLoader.HomogeneousCoordinates = false;
  72304. GLTFFileLoader.IncrementalLoading = true;
  72305. return GLTFFileLoader;
  72306. }());
  72307. BABYLON.GLTFFileLoader = GLTFFileLoader;
  72308. var BinaryReader = (function () {
  72309. function BinaryReader(arrayBuffer) {
  72310. this._arrayBuffer = arrayBuffer;
  72311. this._dataView = new DataView(arrayBuffer);
  72312. this._byteOffset = 0;
  72313. }
  72314. BinaryReader.prototype.getPosition = function () {
  72315. return this._byteOffset;
  72316. };
  72317. BinaryReader.prototype.getLength = function () {
  72318. return this._arrayBuffer.byteLength;
  72319. };
  72320. BinaryReader.prototype.readUint32 = function () {
  72321. var value = this._dataView.getUint32(this._byteOffset, true);
  72322. this._byteOffset += 4;
  72323. return value;
  72324. };
  72325. BinaryReader.prototype.readUint8Array = function (length) {
  72326. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  72327. this._byteOffset += length;
  72328. return value;
  72329. };
  72330. BinaryReader.prototype.skipBytes = function (length) {
  72331. this._byteOffset += length;
  72332. };
  72333. return BinaryReader;
  72334. }());
  72335. if (BABYLON.SceneLoader) {
  72336. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  72337. }
  72338. })(BABYLON || (BABYLON = {}));
  72339. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  72340. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  72341. var BABYLON;
  72342. (function (BABYLON) {
  72343. var GLTF1;
  72344. (function (GLTF1) {
  72345. /**
  72346. * Enums
  72347. */
  72348. var EComponentType;
  72349. (function (EComponentType) {
  72350. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  72351. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  72352. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  72353. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  72354. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  72355. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  72356. var EShaderType;
  72357. (function (EShaderType) {
  72358. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  72359. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  72360. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  72361. var EParameterType;
  72362. (function (EParameterType) {
  72363. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  72364. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  72365. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  72366. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  72367. EParameterType[EParameterType["INT"] = 5124] = "INT";
  72368. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  72369. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  72370. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  72371. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  72372. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  72373. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  72374. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  72375. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  72376. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  72377. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  72378. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  72379. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  72380. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  72381. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  72382. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  72383. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  72384. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  72385. var ETextureWrapMode;
  72386. (function (ETextureWrapMode) {
  72387. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  72388. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  72389. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  72390. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  72391. var ETextureFilterType;
  72392. (function (ETextureFilterType) {
  72393. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  72394. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  72395. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  72396. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  72397. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  72398. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  72399. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  72400. var ETextureFormat;
  72401. (function (ETextureFormat) {
  72402. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  72403. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  72404. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  72405. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  72406. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  72407. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  72408. var ECullingType;
  72409. (function (ECullingType) {
  72410. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  72411. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  72412. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  72413. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  72414. var EBlendingFunction;
  72415. (function (EBlendingFunction) {
  72416. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  72417. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  72418. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  72419. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  72420. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  72421. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  72422. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  72423. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  72424. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  72425. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  72426. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  72427. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  72428. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  72429. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  72430. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  72431. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  72432. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  72433. })(BABYLON || (BABYLON = {}));
  72434. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  72435. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  72436. var BABYLON;
  72437. (function (BABYLON) {
  72438. var GLTF1;
  72439. (function (GLTF1) {
  72440. /**
  72441. * Tokenizer. Used for shaders compatibility
  72442. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  72443. */
  72444. var ETokenType;
  72445. (function (ETokenType) {
  72446. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  72447. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  72448. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  72449. })(ETokenType || (ETokenType = {}));
  72450. var Tokenizer = (function () {
  72451. function Tokenizer(toParse) {
  72452. this._pos = 0;
  72453. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  72454. this._toParse = toParse;
  72455. this._maxPos = toParse.length;
  72456. }
  72457. Tokenizer.prototype.getNextToken = function () {
  72458. if (this.isEnd())
  72459. return ETokenType.END_OF_INPUT;
  72460. this.currentString = this.read();
  72461. this.currentToken = ETokenType.UNKNOWN;
  72462. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  72463. this.currentToken = ETokenType.IDENTIFIER;
  72464. this.currentIdentifier = this.currentString;
  72465. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  72466. this.currentIdentifier += this.currentString;
  72467. this.forward();
  72468. }
  72469. }
  72470. return this.currentToken;
  72471. };
  72472. Tokenizer.prototype.peek = function () {
  72473. return this._toParse[this._pos];
  72474. };
  72475. Tokenizer.prototype.read = function () {
  72476. return this._toParse[this._pos++];
  72477. };
  72478. Tokenizer.prototype.forward = function () {
  72479. this._pos++;
  72480. };
  72481. Tokenizer.prototype.isEnd = function () {
  72482. return this._pos >= this._maxPos;
  72483. };
  72484. return Tokenizer;
  72485. }());
  72486. /**
  72487. * Values
  72488. */
  72489. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  72490. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  72491. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  72492. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  72493. /**
  72494. * Parse
  72495. */
  72496. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  72497. for (var buf in parsedBuffers) {
  72498. var parsedBuffer = parsedBuffers[buf];
  72499. gltfRuntime.buffers[buf] = parsedBuffer;
  72500. gltfRuntime.buffersCount++;
  72501. }
  72502. };
  72503. var parseShaders = function (parsedShaders, gltfRuntime) {
  72504. for (var sha in parsedShaders) {
  72505. var parsedShader = parsedShaders[sha];
  72506. gltfRuntime.shaders[sha] = parsedShader;
  72507. gltfRuntime.shaderscount++;
  72508. }
  72509. };
  72510. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  72511. for (var object in parsedObjects) {
  72512. var parsedObject = parsedObjects[object];
  72513. gltfRuntime[runtimeProperty][object] = parsedObject;
  72514. }
  72515. };
  72516. /**
  72517. * Utils
  72518. */
  72519. var normalizeUVs = function (buffer) {
  72520. if (!buffer) {
  72521. return;
  72522. }
  72523. for (var i = 0; i < buffer.length / 2; i++) {
  72524. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  72525. }
  72526. };
  72527. var replaceInString = function (str, searchValue, replaceValue) {
  72528. while (str.indexOf(searchValue) !== -1) {
  72529. str = str.replace(searchValue, replaceValue);
  72530. }
  72531. return str;
  72532. };
  72533. var getAttribute = function (attributeParameter) {
  72534. if (attributeParameter.semantic === "NORMAL") {
  72535. return "normal";
  72536. }
  72537. else if (attributeParameter.semantic === "POSITION") {
  72538. return "position";
  72539. }
  72540. else if (attributeParameter.semantic === "JOINT") {
  72541. return "matricesIndices";
  72542. }
  72543. else if (attributeParameter.semantic === "WEIGHT") {
  72544. return "matricesWeights";
  72545. }
  72546. else if (attributeParameter.semantic === "COLOR") {
  72547. return "color";
  72548. }
  72549. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  72550. var channel = Number(attributeParameter.semantic.split("_")[1]);
  72551. return "uv" + (channel === 0 ? "" : channel + 1);
  72552. }
  72553. };
  72554. /**
  72555. * Returns the animation path (glTF -> Babylon)
  72556. */
  72557. var getAnimationPath = function (path) {
  72558. var index = glTFAnimationPaths.indexOf(path);
  72559. if (index !== -1) {
  72560. return babylonAnimationPaths[index];
  72561. }
  72562. return path;
  72563. };
  72564. /**
  72565. * Loads and creates animations
  72566. */
  72567. var loadAnimations = function (gltfRuntime) {
  72568. for (var anim in gltfRuntime.animations) {
  72569. var animation = gltfRuntime.animations[anim];
  72570. var lastAnimation = null;
  72571. for (var i = 0; i < animation.channels.length; i++) {
  72572. // Get parameters and load buffers
  72573. var channel = animation.channels[i];
  72574. var sampler = animation.samplers[channel.sampler];
  72575. if (!sampler) {
  72576. continue;
  72577. }
  72578. var inputData = null;
  72579. var outputData = null;
  72580. if (animation.parameters) {
  72581. inputData = animation.parameters[sampler.input];
  72582. outputData = animation.parameters[sampler.output];
  72583. }
  72584. else {
  72585. inputData = sampler.input;
  72586. outputData = sampler.output;
  72587. }
  72588. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  72589. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  72590. var targetID = channel.target.id;
  72591. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  72592. if (targetNode === null) {
  72593. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  72594. }
  72595. if (targetNode === null) {
  72596. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  72597. continue;
  72598. }
  72599. var isBone = targetNode instanceof BABYLON.Bone;
  72600. // Get target path (position, rotation or scaling)
  72601. var targetPath = channel.target.path;
  72602. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  72603. if (targetPathIndex !== -1) {
  72604. targetPath = babylonAnimationPaths[targetPathIndex];
  72605. }
  72606. // Determine animation type
  72607. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  72608. if (!isBone) {
  72609. if (targetPath === "rotationQuaternion") {
  72610. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  72611. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  72612. }
  72613. else {
  72614. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  72615. }
  72616. }
  72617. // Create animation and key frames
  72618. var babylonAnimation = null;
  72619. var keys = [];
  72620. var arrayOffset = 0;
  72621. var modifyKey = false;
  72622. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  72623. babylonAnimation = lastAnimation;
  72624. modifyKey = true;
  72625. }
  72626. if (!modifyKey) {
  72627. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  72628. }
  72629. // For each frame
  72630. for (var j = 0; j < bufferInput.length; j++) {
  72631. var value = null;
  72632. if (targetPath === "rotationQuaternion") {
  72633. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  72634. arrayOffset += 4;
  72635. }
  72636. else {
  72637. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  72638. arrayOffset += 3;
  72639. }
  72640. if (isBone) {
  72641. var bone = targetNode;
  72642. var translation = BABYLON.Vector3.Zero();
  72643. var rotationQuaternion = new BABYLON.Quaternion();
  72644. var scaling = BABYLON.Vector3.Zero();
  72645. // Warning on decompose
  72646. var mat = bone.getBaseMatrix();
  72647. if (modifyKey) {
  72648. mat = lastAnimation.getKeys()[j].value;
  72649. }
  72650. mat.decompose(scaling, rotationQuaternion, translation);
  72651. if (targetPath === "position") {
  72652. translation = value;
  72653. }
  72654. else if (targetPath === "rotationQuaternion") {
  72655. rotationQuaternion = value;
  72656. }
  72657. else {
  72658. scaling = value;
  72659. }
  72660. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  72661. }
  72662. if (!modifyKey) {
  72663. keys.push({
  72664. frame: bufferInput[j],
  72665. value: value
  72666. });
  72667. }
  72668. else {
  72669. lastAnimation.getKeys()[j].value = value;
  72670. }
  72671. }
  72672. // Finish
  72673. if (!modifyKey) {
  72674. babylonAnimation.setKeys(keys);
  72675. targetNode.animations.push(babylonAnimation);
  72676. }
  72677. lastAnimation = babylonAnimation;
  72678. gltfRuntime.scene.stopAnimation(targetNode);
  72679. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  72680. }
  72681. }
  72682. };
  72683. /**
  72684. * Returns the bones transformation matrix
  72685. */
  72686. var configureBoneTransformation = function (node) {
  72687. var mat = null;
  72688. if (node.translation || node.rotation || node.scale) {
  72689. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  72690. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  72691. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  72692. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  72693. }
  72694. else {
  72695. mat = BABYLON.Matrix.FromArray(node.matrix);
  72696. }
  72697. return mat;
  72698. };
  72699. /**
  72700. * Returns the parent bone
  72701. */
  72702. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  72703. // Try to find
  72704. for (var i = 0; i < newSkeleton.bones.length; i++) {
  72705. if (newSkeleton.bones[i].name === jointName) {
  72706. return newSkeleton.bones[i];
  72707. }
  72708. }
  72709. // Not found, search in gltf nodes
  72710. var nodes = gltfRuntime.nodes;
  72711. for (var nde in nodes) {
  72712. var node = nodes[nde];
  72713. if (!node.jointName) {
  72714. continue;
  72715. }
  72716. var children = node.children;
  72717. for (var i = 0; i < children.length; i++) {
  72718. var child = gltfRuntime.nodes[children[i]];
  72719. if (!child.jointName) {
  72720. continue;
  72721. }
  72722. if (child.jointName === jointName) {
  72723. var mat = configureBoneTransformation(node);
  72724. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  72725. bone.id = nde;
  72726. return bone;
  72727. }
  72728. }
  72729. }
  72730. return null;
  72731. };
  72732. /**
  72733. * Returns the appropriate root node
  72734. */
  72735. var getNodeToRoot = function (nodesToRoot, id) {
  72736. for (var i = 0; i < nodesToRoot.length; i++) {
  72737. var nodeToRoot = nodesToRoot[i];
  72738. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  72739. var child = nodeToRoot.node.children[j];
  72740. if (child === id) {
  72741. return nodeToRoot.bone;
  72742. }
  72743. }
  72744. }
  72745. return null;
  72746. };
  72747. /**
  72748. * Returns the node with the joint name
  72749. */
  72750. var getJointNode = function (gltfRuntime, jointName) {
  72751. var nodes = gltfRuntime.nodes;
  72752. var node = nodes[jointName];
  72753. if (node) {
  72754. return {
  72755. node: node,
  72756. id: jointName
  72757. };
  72758. }
  72759. for (var nde in nodes) {
  72760. node = nodes[nde];
  72761. if (node.jointName === jointName) {
  72762. return {
  72763. node: node,
  72764. id: nde
  72765. };
  72766. }
  72767. }
  72768. return null;
  72769. };
  72770. /**
  72771. * Checks if a nodes is in joints
  72772. */
  72773. var nodeIsInJoints = function (skins, id) {
  72774. for (var i = 0; i < skins.jointNames.length; i++) {
  72775. if (skins.jointNames[i] === id) {
  72776. return true;
  72777. }
  72778. }
  72779. return false;
  72780. };
  72781. /**
  72782. * Fills the nodes to root for bones and builds hierarchy
  72783. */
  72784. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  72785. // Creates nodes for root
  72786. for (var nde in gltfRuntime.nodes) {
  72787. var node = gltfRuntime.nodes[nde];
  72788. var id = nde;
  72789. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  72790. continue;
  72791. }
  72792. // Create node to root bone
  72793. var mat = configureBoneTransformation(node);
  72794. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  72795. bone.id = id;
  72796. nodesToRoot.push({ bone: bone, node: node, id: id });
  72797. }
  72798. // Parenting
  72799. for (var i = 0; i < nodesToRoot.length; i++) {
  72800. var nodeToRoot = nodesToRoot[i];
  72801. var children = nodeToRoot.node.children;
  72802. for (var j = 0; j < children.length; j++) {
  72803. var child = null;
  72804. for (var k = 0; k < nodesToRoot.length; k++) {
  72805. if (nodesToRoot[k].id === children[j]) {
  72806. child = nodesToRoot[k];
  72807. break;
  72808. }
  72809. }
  72810. if (child) {
  72811. child.bone._parent = nodeToRoot.bone;
  72812. nodeToRoot.bone.children.push(child.bone);
  72813. }
  72814. }
  72815. }
  72816. };
  72817. var printMat = function (m) {
  72818. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  72819. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  72820. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  72821. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  72822. };
  72823. /**
  72824. * Imports a skeleton
  72825. */
  72826. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  72827. if (!newSkeleton) {
  72828. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  72829. }
  72830. if (!skins.babylonSkeleton) {
  72831. return newSkeleton;
  72832. }
  72833. // Matrices
  72834. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  72835. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  72836. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  72837. // Find the root bones
  72838. var nodesToRoot = [];
  72839. var nodesToRootToAdd = [];
  72840. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  72841. newSkeleton.bones = [];
  72842. // Joints
  72843. for (var i = 0; i < skins.jointNames.length; i++) {
  72844. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  72845. var node = jointNode.node;
  72846. if (!node) {
  72847. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  72848. continue;
  72849. }
  72850. var id = jointNode.id;
  72851. // Optimize, if the bone already exists...
  72852. var existingBone = gltfRuntime.scene.getBoneByID(id);
  72853. if (existingBone) {
  72854. newSkeleton.bones.push(existingBone);
  72855. continue;
  72856. }
  72857. // Search for parent bone
  72858. var foundBone = false;
  72859. var parentBone = null;
  72860. for (var j = 0; j < i; j++) {
  72861. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  72862. if (!joint) {
  72863. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  72864. continue;
  72865. }
  72866. var children = joint.children;
  72867. if (!children) {
  72868. continue;
  72869. }
  72870. foundBone = false;
  72871. for (var k = 0; k < children.length; k++) {
  72872. if (children[k] === id) {
  72873. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  72874. foundBone = true;
  72875. break;
  72876. }
  72877. }
  72878. if (foundBone) {
  72879. break;
  72880. }
  72881. }
  72882. // Create bone
  72883. var mat = configureBoneTransformation(node);
  72884. if (!parentBone && nodesToRoot.length > 0) {
  72885. parentBone = getNodeToRoot(nodesToRoot, id);
  72886. if (parentBone) {
  72887. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  72888. nodesToRootToAdd.push(parentBone);
  72889. }
  72890. }
  72891. }
  72892. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  72893. bone.id = id;
  72894. }
  72895. // Polish
  72896. var bones = newSkeleton.bones;
  72897. newSkeleton.bones = [];
  72898. for (var i = 0; i < skins.jointNames.length; i++) {
  72899. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  72900. if (!jointNode) {
  72901. continue;
  72902. }
  72903. for (var j = 0; j < bones.length; j++) {
  72904. if (bones[j].id === jointNode.id) {
  72905. newSkeleton.bones.push(bones[j]);
  72906. break;
  72907. }
  72908. }
  72909. }
  72910. newSkeleton.prepare();
  72911. // Finish
  72912. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  72913. newSkeleton.bones.push(nodesToRootToAdd[i]);
  72914. }
  72915. return newSkeleton;
  72916. };
  72917. /**
  72918. * Imports a mesh and its geometries
  72919. */
  72920. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  72921. if (!newMesh) {
  72922. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  72923. newMesh.id = id;
  72924. }
  72925. if (!node.babylonNode) {
  72926. return newMesh;
  72927. }
  72928. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  72929. if (!newMesh.material) {
  72930. newMesh.material = multiMat;
  72931. }
  72932. var vertexData = new BABYLON.VertexData();
  72933. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  72934. var verticesStarts = [];
  72935. var verticesCounts = [];
  72936. var indexStarts = [];
  72937. var indexCounts = [];
  72938. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  72939. var meshID = meshes[meshIndex];
  72940. var mesh = gltfRuntime.meshes[meshID];
  72941. if (!mesh) {
  72942. continue;
  72943. }
  72944. // Positions, normals and UVs
  72945. for (var i = 0; i < mesh.primitives.length; i++) {
  72946. // Temporary vertex data
  72947. var tempVertexData = new BABYLON.VertexData();
  72948. var primitive = mesh.primitives[i];
  72949. if (primitive.mode !== 4) {
  72950. // continue;
  72951. }
  72952. var attributes = primitive.attributes;
  72953. var accessor = null;
  72954. var buffer = null;
  72955. // Set positions, normal and uvs
  72956. for (var semantic in attributes) {
  72957. // Link accessor and buffer view
  72958. accessor = gltfRuntime.accessors[attributes[semantic]];
  72959. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  72960. if (semantic === "NORMAL") {
  72961. tempVertexData.normals = new Float32Array(buffer.length);
  72962. tempVertexData.normals.set(buffer);
  72963. }
  72964. else if (semantic === "POSITION") {
  72965. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  72966. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  72967. for (var j = 0; j < buffer.length; j += 4) {
  72968. tempVertexData.positions[j] = buffer[j];
  72969. tempVertexData.positions[j + 1] = buffer[j + 1];
  72970. tempVertexData.positions[j + 2] = buffer[j + 2];
  72971. }
  72972. }
  72973. else {
  72974. tempVertexData.positions = new Float32Array(buffer.length);
  72975. tempVertexData.positions.set(buffer);
  72976. }
  72977. verticesCounts.push(tempVertexData.positions.length);
  72978. }
  72979. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  72980. var channel = Number(semantic.split("_")[1]);
  72981. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  72982. var uvs = new Float32Array(buffer.length);
  72983. uvs.set(buffer);
  72984. normalizeUVs(uvs);
  72985. tempVertexData.set(uvs, uvKind);
  72986. }
  72987. else if (semantic === "JOINT") {
  72988. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  72989. tempVertexData.matricesIndices.set(buffer);
  72990. }
  72991. else if (semantic === "WEIGHT") {
  72992. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  72993. tempVertexData.matricesWeights.set(buffer);
  72994. }
  72995. else if (semantic === "COLOR") {
  72996. tempVertexData.colors = new Float32Array(buffer.length);
  72997. tempVertexData.colors.set(buffer);
  72998. }
  72999. }
  73000. // Indices
  73001. accessor = gltfRuntime.accessors[primitive.indices];
  73002. if (accessor) {
  73003. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73004. tempVertexData.indices = new Int32Array(buffer.length);
  73005. tempVertexData.indices.set(buffer);
  73006. indexCounts.push(tempVertexData.indices.length);
  73007. }
  73008. else {
  73009. // Set indices on the fly
  73010. var indices = [];
  73011. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  73012. indices.push(j);
  73013. }
  73014. tempVertexData.indices = new Int32Array(indices);
  73015. indexCounts.push(tempVertexData.indices.length);
  73016. }
  73017. vertexData.merge(tempVertexData);
  73018. tempVertexData = undefined;
  73019. // Sub material
  73020. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  73021. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  73022. // Update vertices start and index start
  73023. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  73024. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  73025. }
  73026. }
  73027. // Apply geometry
  73028. geometry.setAllVerticesData(vertexData, false);
  73029. newMesh.computeWorldMatrix(true);
  73030. // Apply submeshes
  73031. newMesh.subMeshes = [];
  73032. var index = 0;
  73033. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73034. var meshID = meshes[meshIndex];
  73035. var mesh = gltfRuntime.meshes[meshID];
  73036. if (!mesh) {
  73037. continue;
  73038. }
  73039. for (var i = 0; i < mesh.primitives.length; i++) {
  73040. if (mesh.primitives[i].mode !== 4) {
  73041. //continue;
  73042. }
  73043. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  73044. index++;
  73045. }
  73046. }
  73047. // Finish
  73048. return newMesh;
  73049. };
  73050. /**
  73051. * Configure node transformation from position, rotation and scaling
  73052. */
  73053. var configureNode = function (newNode, position, rotation, scaling) {
  73054. if (newNode.position) {
  73055. newNode.position = position;
  73056. }
  73057. if (newNode.rotationQuaternion || newNode.rotation) {
  73058. newNode.rotationQuaternion = rotation;
  73059. }
  73060. if (newNode.scaling) {
  73061. newNode.scaling = scaling;
  73062. }
  73063. };
  73064. /**
  73065. * Configures node from transformation matrix
  73066. */
  73067. var configureNodeFromMatrix = function (newNode, node, parent) {
  73068. if (node.matrix) {
  73069. var position = new BABYLON.Vector3(0, 0, 0);
  73070. var rotation = new BABYLON.Quaternion();
  73071. var scaling = new BABYLON.Vector3(0, 0, 0);
  73072. var mat = BABYLON.Matrix.FromArray(node.matrix);
  73073. mat.decompose(scaling, rotation, position);
  73074. configureNode(newNode, position, rotation, scaling);
  73075. }
  73076. else {
  73077. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  73078. }
  73079. newNode.computeWorldMatrix(true);
  73080. };
  73081. /**
  73082. * Imports a node
  73083. */
  73084. var importNode = function (gltfRuntime, node, id, parent) {
  73085. var lastNode = null;
  73086. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  73087. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  73088. return null;
  73089. }
  73090. }
  73091. // Meshes
  73092. if (node.skin) {
  73093. if (node.meshes) {
  73094. var skin = gltfRuntime.skins[node.skin];
  73095. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  73096. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  73097. if (newMesh.skeleton === null) {
  73098. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  73099. if (!skin.babylonSkeleton) {
  73100. skin.babylonSkeleton = newMesh.skeleton;
  73101. }
  73102. }
  73103. lastNode = newMesh;
  73104. }
  73105. }
  73106. else if (node.meshes) {
  73107. /**
  73108. * Improve meshes property
  73109. */
  73110. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  73111. lastNode = newMesh;
  73112. }
  73113. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73114. var light = gltfRuntime.lights[node.light];
  73115. if (light) {
  73116. if (light.type === "ambient") {
  73117. var ambienLight = light[light.type];
  73118. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73119. hemiLight.name = node.name;
  73120. if (ambienLight.color) {
  73121. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  73122. }
  73123. lastNode = hemiLight;
  73124. }
  73125. else if (light.type === "directional") {
  73126. var directionalLight = light[light.type];
  73127. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73128. dirLight.name = node.name;
  73129. if (directionalLight.color) {
  73130. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  73131. }
  73132. lastNode = dirLight;
  73133. }
  73134. else if (light.type === "point") {
  73135. var pointLight = light[light.type];
  73136. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73137. ptLight.name = node.name;
  73138. if (pointLight.color) {
  73139. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  73140. }
  73141. lastNode = ptLight;
  73142. }
  73143. else if (light.type === "spot") {
  73144. var spotLight = light[light.type];
  73145. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  73146. spLight.name = node.name;
  73147. if (spotLight.color) {
  73148. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  73149. }
  73150. if (spotLight.fallOfAngle) {
  73151. spLight.angle = spotLight.fallOfAngle;
  73152. }
  73153. if (spotLight.fallOffExponent) {
  73154. spLight.exponent = spotLight.fallOffExponent;
  73155. }
  73156. lastNode = spLight;
  73157. }
  73158. }
  73159. }
  73160. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73161. var camera = gltfRuntime.cameras[node.camera];
  73162. if (camera) {
  73163. if (camera.type === "orthographic") {
  73164. var orthographicCamera = camera[camera.type];
  73165. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73166. orthoCamera.name = node.name;
  73167. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  73168. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73169. lastNode = orthoCamera;
  73170. }
  73171. else if (camera.type === "perspective") {
  73172. var perspectiveCamera = camera[camera.type];
  73173. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73174. persCamera.name = node.name;
  73175. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73176. if (!perspectiveCamera.aspectRatio) {
  73177. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  73178. }
  73179. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  73180. persCamera.maxZ = perspectiveCamera.zfar;
  73181. persCamera.minZ = perspectiveCamera.znear;
  73182. }
  73183. lastNode = persCamera;
  73184. }
  73185. }
  73186. }
  73187. // Empty node
  73188. if (!node.jointName) {
  73189. if (node.babylonNode) {
  73190. return node.babylonNode;
  73191. }
  73192. else if (lastNode === null) {
  73193. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  73194. node.babylonNode = dummy;
  73195. lastNode = dummy;
  73196. }
  73197. }
  73198. if (lastNode !== null) {
  73199. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  73200. configureNodeFromMatrix(lastNode, node, parent);
  73201. }
  73202. else {
  73203. var translation = node.translation || [0, 0, 0];
  73204. var rotation = node.rotation || [0, 0, 0, 1];
  73205. var scale = node.scale || [1, 1, 1];
  73206. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  73207. }
  73208. lastNode.updateCache(true);
  73209. node.babylonNode = lastNode;
  73210. }
  73211. return lastNode;
  73212. };
  73213. /**
  73214. * Traverses nodes and creates them
  73215. */
  73216. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  73217. var node = gltfRuntime.nodes[id];
  73218. var newNode = null;
  73219. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  73220. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  73221. meshIncluded = true;
  73222. }
  73223. else {
  73224. meshIncluded = false;
  73225. }
  73226. }
  73227. else {
  73228. meshIncluded = true;
  73229. }
  73230. if (!node.jointName && meshIncluded) {
  73231. newNode = importNode(gltfRuntime, node, id, parent);
  73232. if (newNode !== null) {
  73233. newNode.id = id;
  73234. newNode.parent = parent;
  73235. }
  73236. }
  73237. if (node.children) {
  73238. for (var i = 0; i < node.children.length; i++) {
  73239. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  73240. }
  73241. }
  73242. };
  73243. /**
  73244. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  73245. */
  73246. var postLoad = function (gltfRuntime) {
  73247. // Nodes
  73248. var currentScene = gltfRuntime.currentScene;
  73249. if (currentScene) {
  73250. for (var i = 0; i < currentScene.nodes.length; i++) {
  73251. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73252. }
  73253. }
  73254. else {
  73255. for (var thing in gltfRuntime.scenes) {
  73256. currentScene = gltfRuntime.scenes[thing];
  73257. for (var i = 0; i < currentScene.nodes.length; i++) {
  73258. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73259. }
  73260. }
  73261. }
  73262. // Set animations
  73263. loadAnimations(gltfRuntime);
  73264. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  73265. var skeleton = gltfRuntime.scene.skeletons[i];
  73266. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  73267. }
  73268. };
  73269. /**
  73270. * onBind shaderrs callback to set uniforms and matrices
  73271. */
  73272. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  73273. var materialValues = material.values || technique.parameters;
  73274. for (var unif in unTreatedUniforms) {
  73275. var uniform = unTreatedUniforms[unif];
  73276. var type = uniform.type;
  73277. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  73278. if (uniform.semantic && !uniform.source && !uniform.node) {
  73279. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  73280. }
  73281. else if (uniform.semantic && (uniform.source || uniform.node)) {
  73282. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  73283. if (source === null) {
  73284. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  73285. }
  73286. if (source === null) {
  73287. continue;
  73288. }
  73289. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  73290. }
  73291. }
  73292. else {
  73293. var value = materialValues[technique.uniforms[unif]];
  73294. if (!value) {
  73295. continue;
  73296. }
  73297. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  73298. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  73299. if (texture === null || texture === undefined) {
  73300. continue;
  73301. }
  73302. shaderMaterial.getEffect().setTexture(unif, texture);
  73303. }
  73304. else {
  73305. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  73306. }
  73307. }
  73308. }
  73309. onSuccess(shaderMaterial);
  73310. };
  73311. /**
  73312. * Prepare uniforms to send the only one time
  73313. * Loads the appropriate textures
  73314. */
  73315. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  73316. var materialValues = material.values || technique.parameters;
  73317. var techniqueUniforms = technique.uniforms;
  73318. /**
  73319. * Prepare values here (not matrices)
  73320. */
  73321. for (var unif in unTreatedUniforms) {
  73322. var uniform = unTreatedUniforms[unif];
  73323. var type = uniform.type;
  73324. var value = materialValues[techniqueUniforms[unif]];
  73325. if (value === undefined) {
  73326. // In case the value is the same for all materials
  73327. value = uniform.value;
  73328. }
  73329. if (!value) {
  73330. continue;
  73331. }
  73332. var onLoadTexture = function (uniformName) {
  73333. return function (texture) {
  73334. if (uniform.value) {
  73335. // Static uniform
  73336. shaderMaterial.setTexture(uniformName, texture);
  73337. delete unTreatedUniforms[uniformName];
  73338. }
  73339. };
  73340. };
  73341. // Texture (sampler2D)
  73342. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  73343. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  73344. }
  73345. else {
  73346. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  73347. // Static uniform
  73348. delete unTreatedUniforms[unif];
  73349. }
  73350. }
  73351. }
  73352. };
  73353. /**
  73354. * Shader compilation failed
  73355. */
  73356. var onShaderCompileError = function (program, shaderMaterial, onError) {
  73357. return function (effect, error) {
  73358. shaderMaterial.dispose(true);
  73359. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  73360. };
  73361. };
  73362. /**
  73363. * Shader compilation success
  73364. */
  73365. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  73366. return function (_) {
  73367. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  73368. shaderMaterial.onBind = function (mesh) {
  73369. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  73370. };
  73371. };
  73372. };
  73373. /**
  73374. * Returns the appropriate uniform if already handled by babylon
  73375. */
  73376. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  73377. for (var unif in technique.uniforms) {
  73378. var uniform = technique.uniforms[unif];
  73379. var uniformParameter = technique.parameters[uniform];
  73380. if (tokenizer.currentIdentifier === unif) {
  73381. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  73382. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  73383. if (transformIndex !== -1) {
  73384. delete unTreatedUniforms[unif];
  73385. return babylonTransforms[transformIndex];
  73386. }
  73387. }
  73388. }
  73389. }
  73390. return tokenizer.currentIdentifier;
  73391. };
  73392. /**
  73393. * All shaders loaded. Create materials one by one
  73394. */
  73395. var importMaterials = function (gltfRuntime) {
  73396. // Create materials
  73397. for (var mat in gltfRuntime.materials) {
  73398. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  73399. }
  73400. };
  73401. /**
  73402. * Implementation of the base glTF spec
  73403. */
  73404. var GLTFLoaderBase = (function () {
  73405. function GLTFLoaderBase() {
  73406. }
  73407. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  73408. var gltfRuntime = {
  73409. extensions: {},
  73410. accessors: {},
  73411. buffers: {},
  73412. bufferViews: {},
  73413. meshes: {},
  73414. lights: {},
  73415. cameras: {},
  73416. nodes: {},
  73417. images: {},
  73418. textures: {},
  73419. shaders: {},
  73420. programs: {},
  73421. samplers: {},
  73422. techniques: {},
  73423. materials: {},
  73424. animations: {},
  73425. skins: {},
  73426. extensionsUsed: [],
  73427. scenes: {},
  73428. buffersCount: 0,
  73429. shaderscount: 0,
  73430. scene: scene,
  73431. rootUrl: rootUrl,
  73432. loadedBufferCount: 0,
  73433. loadedBufferViews: {},
  73434. loadedShaderCount: 0,
  73435. importOnlyMeshes: false,
  73436. dummyNodes: []
  73437. };
  73438. // Parse
  73439. if (parsedData.extensions) {
  73440. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  73441. }
  73442. if (parsedData.extensionsUsed) {
  73443. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  73444. }
  73445. if (parsedData.buffers) {
  73446. parseBuffers(parsedData.buffers, gltfRuntime);
  73447. }
  73448. if (parsedData.bufferViews) {
  73449. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  73450. }
  73451. if (parsedData.accessors) {
  73452. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  73453. }
  73454. if (parsedData.meshes) {
  73455. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  73456. }
  73457. if (parsedData.lights) {
  73458. parseObject(parsedData.lights, "lights", gltfRuntime);
  73459. }
  73460. if (parsedData.cameras) {
  73461. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  73462. }
  73463. if (parsedData.nodes) {
  73464. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  73465. }
  73466. if (parsedData.images) {
  73467. parseObject(parsedData.images, "images", gltfRuntime);
  73468. }
  73469. if (parsedData.textures) {
  73470. parseObject(parsedData.textures, "textures", gltfRuntime);
  73471. }
  73472. if (parsedData.shaders) {
  73473. parseShaders(parsedData.shaders, gltfRuntime);
  73474. }
  73475. if (parsedData.programs) {
  73476. parseObject(parsedData.programs, "programs", gltfRuntime);
  73477. }
  73478. if (parsedData.samplers) {
  73479. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  73480. }
  73481. if (parsedData.techniques) {
  73482. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  73483. }
  73484. if (parsedData.materials) {
  73485. parseObject(parsedData.materials, "materials", gltfRuntime);
  73486. }
  73487. if (parsedData.animations) {
  73488. parseObject(parsedData.animations, "animations", gltfRuntime);
  73489. }
  73490. if (parsedData.skins) {
  73491. parseObject(parsedData.skins, "skins", gltfRuntime);
  73492. }
  73493. if (parsedData.scenes) {
  73494. gltfRuntime.scenes = parsedData.scenes;
  73495. }
  73496. if (parsedData.scene && parsedData.scenes) {
  73497. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  73498. }
  73499. return gltfRuntime;
  73500. };
  73501. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  73502. var buffer = gltfRuntime.buffers[id];
  73503. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  73504. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  73505. }
  73506. else {
  73507. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  73508. onError(request.status + " " + request.statusText);
  73509. });
  73510. }
  73511. };
  73512. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  73513. var texture = gltfRuntime.textures[id];
  73514. if (!texture || !texture.source) {
  73515. onError(null);
  73516. return;
  73517. }
  73518. if (texture.babylonTexture) {
  73519. onSuccess(null);
  73520. return;
  73521. }
  73522. var source = gltfRuntime.images[texture.source];
  73523. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  73524. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  73525. }
  73526. else {
  73527. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  73528. onError(request.status + " " + request.statusText);
  73529. });
  73530. }
  73531. };
  73532. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  73533. var texture = gltfRuntime.textures[id];
  73534. if (texture.babylonTexture) {
  73535. onSuccess(texture.babylonTexture);
  73536. return;
  73537. }
  73538. var sampler = gltfRuntime.samplers[texture.sampler];
  73539. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  73540. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  73541. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  73542. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  73543. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  73544. var blob = new Blob([buffer]);
  73545. var blobURL = URL.createObjectURL(blob);
  73546. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  73547. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  73548. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  73549. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  73550. newTexture.name = id;
  73551. texture.babylonTexture = newTexture;
  73552. onSuccess(newTexture);
  73553. };
  73554. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  73555. var shader = gltfRuntime.shaders[id];
  73556. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  73557. var shaderString = atob(shader.uri.split(",")[1]);
  73558. onSuccess(shaderString);
  73559. }
  73560. else {
  73561. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  73562. onError(request.status + " " + request.statusText);
  73563. });
  73564. }
  73565. };
  73566. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  73567. var material = gltfRuntime.materials[id];
  73568. var technique = gltfRuntime.techniques[material.technique];
  73569. if (!technique) {
  73570. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  73571. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  73572. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  73573. onSuccess(defaultMaterial);
  73574. return;
  73575. }
  73576. var program = gltfRuntime.programs[technique.program];
  73577. var states = technique.states;
  73578. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  73579. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  73580. var newVertexShader = "";
  73581. var newPixelShader = "";
  73582. var vertexTokenizer = new Tokenizer(vertexShader);
  73583. var pixelTokenizer = new Tokenizer(pixelShader);
  73584. var unTreatedUniforms = {};
  73585. var uniforms = [];
  73586. var attributes = [];
  73587. var samplers = [];
  73588. // Fill uniform, sampler2D and attributes
  73589. for (var unif in technique.uniforms) {
  73590. var uniform = technique.uniforms[unif];
  73591. var uniformParameter = technique.parameters[uniform];
  73592. unTreatedUniforms[unif] = uniformParameter;
  73593. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  73594. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  73595. if (transformIndex !== -1) {
  73596. uniforms.push(babylonTransforms[transformIndex]);
  73597. delete unTreatedUniforms[unif];
  73598. }
  73599. else {
  73600. uniforms.push(unif);
  73601. }
  73602. }
  73603. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  73604. samplers.push(unif);
  73605. }
  73606. else {
  73607. uniforms.push(unif);
  73608. }
  73609. }
  73610. for (var attr in technique.attributes) {
  73611. var attribute = technique.attributes[attr];
  73612. var attributeParameter = technique.parameters[attribute];
  73613. if (attributeParameter.semantic) {
  73614. attributes.push(getAttribute(attributeParameter));
  73615. }
  73616. }
  73617. // Configure vertex shader
  73618. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  73619. var tokenType = vertexTokenizer.currentToken;
  73620. if (tokenType !== ETokenType.IDENTIFIER) {
  73621. newVertexShader += vertexTokenizer.currentString;
  73622. continue;
  73623. }
  73624. var foundAttribute = false;
  73625. for (var attr in technique.attributes) {
  73626. var attribute = technique.attributes[attr];
  73627. var attributeParameter = technique.parameters[attribute];
  73628. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  73629. newVertexShader += getAttribute(attributeParameter);
  73630. foundAttribute = true;
  73631. break;
  73632. }
  73633. }
  73634. if (foundAttribute) {
  73635. continue;
  73636. }
  73637. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  73638. }
  73639. // Configure pixel shader
  73640. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  73641. var tokenType = pixelTokenizer.currentToken;
  73642. if (tokenType !== ETokenType.IDENTIFIER) {
  73643. newPixelShader += pixelTokenizer.currentString;
  73644. continue;
  73645. }
  73646. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  73647. }
  73648. // Create shader material
  73649. var shaderPath = {
  73650. vertex: program.vertexShader + id,
  73651. fragment: program.fragmentShader + id
  73652. };
  73653. var options = {
  73654. attributes: attributes,
  73655. uniforms: uniforms,
  73656. samplers: samplers,
  73657. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  73658. };
  73659. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  73660. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  73661. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  73662. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  73663. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  73664. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  73665. if (states && states.functions) {
  73666. var functions = states.functions;
  73667. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  73668. shaderMaterial.backFaceCulling = false;
  73669. }
  73670. var blendFunc = functions.blendFuncSeparate;
  73671. if (blendFunc) {
  73672. 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) {
  73673. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  73674. }
  73675. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  73676. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  73677. }
  73678. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  73679. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  73680. }
  73681. 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) {
  73682. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  73683. }
  73684. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  73685. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  73686. }
  73687. 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) {
  73688. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  73689. }
  73690. }
  73691. }
  73692. };
  73693. return GLTFLoaderBase;
  73694. }());
  73695. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  73696. /**
  73697. * glTF V1 Loader
  73698. */
  73699. var GLTFLoader = (function () {
  73700. function GLTFLoader() {
  73701. }
  73702. GLTFLoader.RegisterExtension = function (extension) {
  73703. if (GLTFLoader.Extensions[extension.name]) {
  73704. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  73705. return;
  73706. }
  73707. GLTFLoader.Extensions[extension.name] = extension;
  73708. };
  73709. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  73710. var _this = this;
  73711. scene.useRightHandedSystem = true;
  73712. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  73713. gltfRuntime.importOnlyMeshes = true;
  73714. if (meshesNames === "") {
  73715. gltfRuntime.importMeshesNames = [];
  73716. }
  73717. else if (typeof meshesNames === "string") {
  73718. gltfRuntime.importMeshesNames = [meshesNames];
  73719. }
  73720. else if (meshesNames && !(meshesNames instanceof Array)) {
  73721. gltfRuntime.importMeshesNames = [meshesNames];
  73722. }
  73723. else {
  73724. gltfRuntime.importMeshesNames = [];
  73725. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  73726. }
  73727. // Create nodes
  73728. _this._createNodes(gltfRuntime);
  73729. var meshes = [];
  73730. var skeletons = [];
  73731. // Fill arrays of meshes and skeletons
  73732. for (var nde in gltfRuntime.nodes) {
  73733. var node = gltfRuntime.nodes[nde];
  73734. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  73735. meshes.push(node.babylonNode);
  73736. }
  73737. }
  73738. for (var skl in gltfRuntime.skins) {
  73739. var skin = gltfRuntime.skins[skl];
  73740. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  73741. skeletons.push(skin.babylonSkeleton);
  73742. }
  73743. }
  73744. // Load buffers, shaders, materials, etc.
  73745. _this._loadBuffersAsync(gltfRuntime, function () {
  73746. _this._loadShadersAsync(gltfRuntime, function () {
  73747. importMaterials(gltfRuntime);
  73748. postLoad(gltfRuntime);
  73749. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  73750. onSuccess(meshes, null, skeletons);
  73751. }
  73752. });
  73753. }, onProgress);
  73754. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  73755. onSuccess(meshes, null, skeletons);
  73756. }
  73757. }, onError);
  73758. return true;
  73759. };
  73760. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  73761. var _this = this;
  73762. scene.useRightHandedSystem = true;
  73763. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  73764. // Load runtime extensios
  73765. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  73766. // Create nodes
  73767. _this._createNodes(gltfRuntime);
  73768. // Load buffers, shaders, materials, etc.
  73769. _this._loadBuffersAsync(gltfRuntime, function () {
  73770. _this._loadShadersAsync(gltfRuntime, function () {
  73771. importMaterials(gltfRuntime);
  73772. postLoad(gltfRuntime);
  73773. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  73774. onSuccess();
  73775. }
  73776. });
  73777. });
  73778. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  73779. onSuccess();
  73780. }
  73781. }, onError);
  73782. }, onError);
  73783. };
  73784. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  73785. var hasShaders = false;
  73786. var processShader = function (sha, shader) {
  73787. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  73788. gltfRuntime.loadedShaderCount++;
  73789. if (shaderString) {
  73790. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  73791. }
  73792. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  73793. onload();
  73794. }
  73795. }, function () {
  73796. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  73797. });
  73798. };
  73799. for (var sha in gltfRuntime.shaders) {
  73800. hasShaders = true;
  73801. var shader = gltfRuntime.shaders[sha];
  73802. if (shader) {
  73803. processShader.bind(this, sha, shader)();
  73804. }
  73805. else {
  73806. BABYLON.Tools.Error("No shader named: " + sha);
  73807. }
  73808. }
  73809. if (!hasShaders) {
  73810. onload();
  73811. }
  73812. };
  73813. ;
  73814. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  73815. var hasBuffers = false;
  73816. var processBuffer = function (buf, buffer) {
  73817. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  73818. gltfRuntime.loadedBufferCount++;
  73819. if (bufferView) {
  73820. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  73821. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  73822. }
  73823. gltfRuntime.loadedBufferViews[buf] = bufferView;
  73824. }
  73825. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  73826. onLoad();
  73827. }
  73828. }, function () {
  73829. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  73830. });
  73831. };
  73832. for (var buf in gltfRuntime.buffers) {
  73833. hasBuffers = true;
  73834. var buffer = gltfRuntime.buffers[buf];
  73835. if (buffer) {
  73836. processBuffer.bind(this, buf, buffer)();
  73837. }
  73838. else {
  73839. BABYLON.Tools.Error("No buffer named: " + buf);
  73840. }
  73841. }
  73842. if (!hasBuffers) {
  73843. onLoad();
  73844. }
  73845. };
  73846. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  73847. var currentScene = gltfRuntime.currentScene;
  73848. if (currentScene) {
  73849. // Only one scene even if multiple scenes are defined
  73850. for (var i = 0; i < currentScene.nodes.length; i++) {
  73851. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73852. }
  73853. }
  73854. else {
  73855. // Load all scenes
  73856. for (var thing in gltfRuntime.scenes) {
  73857. currentScene = gltfRuntime.scenes[thing];
  73858. for (var i = 0; i < currentScene.nodes.length; i++) {
  73859. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73860. }
  73861. }
  73862. }
  73863. };
  73864. GLTFLoader.Extensions = {};
  73865. return GLTFLoader;
  73866. }());
  73867. GLTF1.GLTFLoader = GLTFLoader;
  73868. ;
  73869. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  73870. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73871. })(BABYLON || (BABYLON = {}));
  73872. //# sourceMappingURL=babylon.glTFLoader.js.map
  73873. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73874. var BABYLON;
  73875. (function (BABYLON) {
  73876. var GLTF1;
  73877. (function (GLTF1) {
  73878. /**
  73879. * Utils functions for GLTF
  73880. */
  73881. var GLTFUtils = (function () {
  73882. function GLTFUtils() {
  73883. }
  73884. /**
  73885. * Sets the given "parameter" matrix
  73886. * @param scene: the {BABYLON.Scene} object
  73887. * @param source: the source node where to pick the matrix
  73888. * @param parameter: the GLTF technique parameter
  73889. * @param uniformName: the name of the shader's uniform
  73890. * @param shaderMaterial: the shader material
  73891. */
  73892. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  73893. var mat = null;
  73894. if (parameter.semantic === "MODEL") {
  73895. mat = source.getWorldMatrix();
  73896. }
  73897. else if (parameter.semantic === "PROJECTION") {
  73898. mat = scene.getProjectionMatrix();
  73899. }
  73900. else if (parameter.semantic === "VIEW") {
  73901. mat = scene.getViewMatrix();
  73902. }
  73903. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  73904. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  73905. }
  73906. else if (parameter.semantic === "MODELVIEW") {
  73907. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  73908. }
  73909. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  73910. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  73911. }
  73912. else if (parameter.semantic === "MODELINVERSE") {
  73913. mat = source.getWorldMatrix().invert();
  73914. }
  73915. else if (parameter.semantic === "VIEWINVERSE") {
  73916. mat = scene.getViewMatrix().invert();
  73917. }
  73918. else if (parameter.semantic === "PROJECTIONINVERSE") {
  73919. mat = scene.getProjectionMatrix().invert();
  73920. }
  73921. else if (parameter.semantic === "MODELVIEWINVERSE") {
  73922. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  73923. }
  73924. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  73925. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  73926. }
  73927. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  73928. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  73929. }
  73930. else {
  73931. debugger;
  73932. }
  73933. switch (parameter.type) {
  73934. case GLTF1.EParameterType.FLOAT_MAT2:
  73935. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  73936. break;
  73937. case GLTF1.EParameterType.FLOAT_MAT3:
  73938. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  73939. break;
  73940. case GLTF1.EParameterType.FLOAT_MAT4:
  73941. shaderMaterial.setMatrix(uniformName, mat);
  73942. break;
  73943. default: break;
  73944. }
  73945. };
  73946. /**
  73947. * Sets the given "parameter" matrix
  73948. * @param shaderMaterial: the shader material
  73949. * @param uniform: the name of the shader's uniform
  73950. * @param value: the value of the uniform
  73951. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  73952. */
  73953. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  73954. switch (type) {
  73955. case GLTF1.EParameterType.FLOAT:
  73956. shaderMaterial.setFloat(uniform, value);
  73957. return true;
  73958. case GLTF1.EParameterType.FLOAT_VEC2:
  73959. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  73960. return true;
  73961. case GLTF1.EParameterType.FLOAT_VEC3:
  73962. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  73963. return true;
  73964. case GLTF1.EParameterType.FLOAT_VEC4:
  73965. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  73966. return true;
  73967. default: return false;
  73968. }
  73969. };
  73970. /**
  73971. * If the uri is a base64 string
  73972. * @param uri: the uri to test
  73973. */
  73974. GLTFUtils.IsBase64 = function (uri) {
  73975. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  73976. };
  73977. /**
  73978. * Decode the base64 uri
  73979. * @param uri: the uri to decode
  73980. */
  73981. GLTFUtils.DecodeBase64 = function (uri) {
  73982. var decodedString = atob(uri.split(",")[1]);
  73983. var bufferLength = decodedString.length;
  73984. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  73985. for (var i = 0; i < bufferLength; i++) {
  73986. bufferView[i] = decodedString.charCodeAt(i);
  73987. }
  73988. return bufferView.buffer;
  73989. };
  73990. /**
  73991. * Returns the wrap mode of the texture
  73992. * @param mode: the mode value
  73993. */
  73994. GLTFUtils.GetWrapMode = function (mode) {
  73995. switch (mode) {
  73996. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  73997. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  73998. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  73999. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74000. }
  74001. };
  74002. /**
  74003. * Returns the byte stride giving an accessor
  74004. * @param accessor: the GLTF accessor objet
  74005. */
  74006. GLTFUtils.GetByteStrideFromType = function (accessor) {
  74007. // Needs this function since "byteStride" isn't requiered in glTF format
  74008. var type = accessor.type;
  74009. switch (type) {
  74010. case "VEC2": return 2;
  74011. case "VEC3": return 3;
  74012. case "VEC4": return 4;
  74013. case "MAT2": return 4;
  74014. case "MAT3": return 9;
  74015. case "MAT4": return 16;
  74016. default: return 1;
  74017. }
  74018. };
  74019. /**
  74020. * Returns the texture filter mode giving a mode value
  74021. * @param mode: the filter mode value
  74022. */
  74023. GLTFUtils.GetTextureFilterMode = function (mode) {
  74024. switch (mode) {
  74025. case GLTF1.ETextureFilterType.LINEAR:
  74026. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  74027. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  74028. case GLTF1.ETextureFilterType.NEAREST:
  74029. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  74030. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  74031. }
  74032. };
  74033. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  74034. var byteOffset = bufferView.byteOffset + byteOffset;
  74035. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  74036. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  74037. throw new Error("Buffer access is out of range");
  74038. }
  74039. var buffer = loadedBufferView.buffer;
  74040. byteOffset += loadedBufferView.byteOffset;
  74041. switch (componentType) {
  74042. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  74043. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  74044. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  74045. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  74046. default: return new Float32Array(buffer, byteOffset, byteLength);
  74047. }
  74048. };
  74049. /**
  74050. * Returns a buffer from its accessor
  74051. * @param gltfRuntime: the GLTF runtime
  74052. * @param accessor: the GLTF accessor
  74053. */
  74054. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  74055. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  74056. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  74057. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  74058. };
  74059. /**
  74060. * Decodes a buffer view into a string
  74061. * @param view: the buffer view
  74062. */
  74063. GLTFUtils.DecodeBufferToText = function (view) {
  74064. var result = "";
  74065. var length = view.byteLength;
  74066. for (var i = 0; i < length; ++i) {
  74067. result += String.fromCharCode(view[i]);
  74068. }
  74069. return result;
  74070. };
  74071. /**
  74072. * Returns the default material of gltf. Related to
  74073. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  74074. * @param scene: the Babylon.js scene
  74075. */
  74076. GLTFUtils.GetDefaultMaterial = function (scene) {
  74077. if (!GLTFUtils._DefaultMaterial) {
  74078. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  74079. "precision highp float;",
  74080. "",
  74081. "uniform mat4 worldView;",
  74082. "uniform mat4 projection;",
  74083. "",
  74084. "attribute vec3 position;",
  74085. "",
  74086. "void main(void)",
  74087. "{",
  74088. " gl_Position = projection * worldView * vec4(position, 1.0);",
  74089. "}"
  74090. ].join("\n");
  74091. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  74092. "precision highp float;",
  74093. "",
  74094. "uniform vec4 u_emission;",
  74095. "",
  74096. "void main(void)",
  74097. "{",
  74098. " gl_FragColor = u_emission;",
  74099. "}"
  74100. ].join("\n");
  74101. var shaderPath = {
  74102. vertex: "GLTFDefaultMaterial",
  74103. fragment: "GLTFDefaultMaterial"
  74104. };
  74105. var options = {
  74106. attributes: ["position"],
  74107. uniforms: ["worldView", "projection", "u_emission"],
  74108. samplers: [],
  74109. needAlphaBlending: false
  74110. };
  74111. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  74112. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  74113. }
  74114. return GLTFUtils._DefaultMaterial;
  74115. };
  74116. // The GLTF default material
  74117. GLTFUtils._DefaultMaterial = null;
  74118. return GLTFUtils;
  74119. }());
  74120. GLTF1.GLTFUtils = GLTFUtils;
  74121. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74122. })(BABYLON || (BABYLON = {}));
  74123. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  74124. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74125. var BABYLON;
  74126. (function (BABYLON) {
  74127. var GLTF1;
  74128. (function (GLTF1) {
  74129. var GLTFLoaderExtension = (function () {
  74130. function GLTFLoaderExtension(name) {
  74131. this._name = name;
  74132. }
  74133. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  74134. get: function () {
  74135. return this._name;
  74136. },
  74137. enumerable: true,
  74138. configurable: true
  74139. });
  74140. /**
  74141. * Defines an override for loading the runtime
  74142. * Return true to stop further extensions from loading the runtime
  74143. */
  74144. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74145. return false;
  74146. };
  74147. /**
  74148. * Defines an onverride for creating gltf runtime
  74149. * Return true to stop further extensions from creating the runtime
  74150. */
  74151. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74152. return false;
  74153. };
  74154. /**
  74155. * Defines an override for loading buffers
  74156. * Return true to stop further extensions from loading this buffer
  74157. */
  74158. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74159. return false;
  74160. };
  74161. /**
  74162. * Defines an override for loading texture buffers
  74163. * Return true to stop further extensions from loading this texture data
  74164. */
  74165. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74166. return false;
  74167. };
  74168. /**
  74169. * Defines an override for creating textures
  74170. * Return true to stop further extensions from loading this texture
  74171. */
  74172. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74173. return false;
  74174. };
  74175. /**
  74176. * Defines an override for loading shader strings
  74177. * Return true to stop further extensions from loading this shader data
  74178. */
  74179. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74180. return false;
  74181. };
  74182. /**
  74183. * Defines an override for loading materials
  74184. * Return true to stop further extensions from loading this material
  74185. */
  74186. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74187. return false;
  74188. };
  74189. // ---------
  74190. // Utilities
  74191. // ---------
  74192. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74193. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74194. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  74195. }, function () {
  74196. setTimeout(function () {
  74197. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  74198. });
  74199. });
  74200. };
  74201. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74202. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74203. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  74204. }, function () {
  74205. setTimeout(function () {
  74206. onSuccess();
  74207. });
  74208. });
  74209. };
  74210. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74211. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74212. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  74213. }, function () {
  74214. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  74215. });
  74216. };
  74217. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  74218. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  74219. };
  74220. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74221. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74222. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74223. }, function () {
  74224. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74225. });
  74226. };
  74227. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74228. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74229. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74230. }, function () {
  74231. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74232. });
  74233. };
  74234. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74235. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74236. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  74237. }, function () {
  74238. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  74239. });
  74240. };
  74241. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74242. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74243. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  74244. }, function () {
  74245. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  74246. });
  74247. };
  74248. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  74249. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  74250. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  74251. if (func(loaderExtension)) {
  74252. return;
  74253. }
  74254. }
  74255. defaultFunc();
  74256. };
  74257. return GLTFLoaderExtension;
  74258. }());
  74259. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  74260. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74261. })(BABYLON || (BABYLON = {}));
  74262. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  74263. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74264. var BABYLON;
  74265. (function (BABYLON) {
  74266. var GLTF1;
  74267. (function (GLTF1) {
  74268. var BinaryExtensionBufferName = "binary_glTF";
  74269. var EContentFormat;
  74270. (function (EContentFormat) {
  74271. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  74272. })(EContentFormat || (EContentFormat = {}));
  74273. ;
  74274. ;
  74275. ;
  74276. var GLTFBinaryExtension = (function (_super) {
  74277. __extends(GLTFBinaryExtension, _super);
  74278. function GLTFBinaryExtension() {
  74279. return _super.call(this, "KHR_binary_glTF") || this;
  74280. }
  74281. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74282. var extensionsUsed = data.json.extensionsUsed;
  74283. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  74284. return false;
  74285. }
  74286. this._bin = data.bin;
  74287. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  74288. return true;
  74289. };
  74290. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74291. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  74292. return false;
  74293. }
  74294. if (id !== BinaryExtensionBufferName) {
  74295. return false;
  74296. }
  74297. onSuccess(this._bin);
  74298. return true;
  74299. };
  74300. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74301. var texture = gltfRuntime.textures[id];
  74302. var source = gltfRuntime.images[texture.source];
  74303. if (!source.extensions || !(this.name in source.extensions)) {
  74304. return false;
  74305. }
  74306. var sourceExt = source.extensions[this.name];
  74307. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  74308. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  74309. onSuccess(buffer);
  74310. return true;
  74311. };
  74312. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74313. var shader = gltfRuntime.shaders[id];
  74314. if (!shader.extensions || !(this.name in shader.extensions)) {
  74315. return false;
  74316. }
  74317. var binaryExtensionShader = shader.extensions[this.name];
  74318. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  74319. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  74320. setTimeout(function () {
  74321. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  74322. onSuccess(shaderString);
  74323. });
  74324. return true;
  74325. };
  74326. return GLTFBinaryExtension;
  74327. }(GLTF1.GLTFLoaderExtension));
  74328. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  74329. var BinaryReader = (function () {
  74330. function BinaryReader(arrayBuffer) {
  74331. this._arrayBuffer = arrayBuffer;
  74332. this._dataView = new DataView(arrayBuffer);
  74333. this._byteOffset = 0;
  74334. }
  74335. BinaryReader.prototype.getUint32 = function () {
  74336. var value = this._dataView.getUint32(this._byteOffset, true);
  74337. this._byteOffset += 4;
  74338. return value;
  74339. };
  74340. BinaryReader.prototype.getUint8Array = function (length) {
  74341. if (!length) {
  74342. length = this._arrayBuffer.byteLength - this._byteOffset;
  74343. }
  74344. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  74345. this._byteOffset += length;
  74346. return value;
  74347. };
  74348. return BinaryReader;
  74349. }());
  74350. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  74351. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74352. })(BABYLON || (BABYLON = {}));
  74353. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  74354. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74355. var BABYLON;
  74356. (function (BABYLON) {
  74357. var GLTF1;
  74358. (function (GLTF1) {
  74359. ;
  74360. ;
  74361. ;
  74362. var GLTFMaterialsCommonExtension = (function (_super) {
  74363. __extends(GLTFMaterialsCommonExtension, _super);
  74364. function GLTFMaterialsCommonExtension() {
  74365. return _super.call(this, "KHR_materials_common") || this;
  74366. }
  74367. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74368. if (!gltfRuntime.extensions)
  74369. return false;
  74370. var extension = gltfRuntime.extensions[this.name];
  74371. if (!extension)
  74372. return false;
  74373. // Create lights
  74374. var lights = extension.lights;
  74375. if (lights) {
  74376. for (var thing in lights) {
  74377. var light = lights[thing];
  74378. switch (light.type) {
  74379. case "ambient":
  74380. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  74381. var ambient = light.ambient;
  74382. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  74383. break;
  74384. case "point":
  74385. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  74386. var point = light.point;
  74387. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  74388. break;
  74389. case "directional":
  74390. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  74391. var directional = light.directional;
  74392. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  74393. break;
  74394. case "spot":
  74395. var spot = light.spot;
  74396. 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);
  74397. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  74398. break;
  74399. default:
  74400. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  74401. break;
  74402. }
  74403. }
  74404. }
  74405. return false;
  74406. };
  74407. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74408. var material = gltfRuntime.materials[id];
  74409. if (!material || !material.extensions)
  74410. return false;
  74411. var extension = material.extensions[this.name];
  74412. if (!extension)
  74413. return false;
  74414. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  74415. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74416. if (extension.technique === "CONSTANT") {
  74417. standardMaterial.disableLighting = true;
  74418. }
  74419. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  74420. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  74421. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  74422. // Ambient
  74423. if (typeof extension.values.ambient === "string") {
  74424. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  74425. }
  74426. else {
  74427. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  74428. }
  74429. // Diffuse
  74430. if (typeof extension.values.diffuse === "string") {
  74431. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  74432. }
  74433. else {
  74434. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  74435. }
  74436. // Emission
  74437. if (typeof extension.values.emission === "string") {
  74438. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  74439. }
  74440. else {
  74441. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  74442. }
  74443. // Specular
  74444. if (typeof extension.values.specular === "string") {
  74445. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  74446. }
  74447. else {
  74448. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  74449. }
  74450. return true;
  74451. };
  74452. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  74453. // Create buffer from texture url
  74454. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  74455. // Create texture from buffer
  74456. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  74457. }, onError);
  74458. };
  74459. return GLTFMaterialsCommonExtension;
  74460. }(GLTF1.GLTFLoaderExtension));
  74461. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  74462. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  74463. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74464. })(BABYLON || (BABYLON = {}));
  74465. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  74466. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74467. var BABYLON;
  74468. (function (BABYLON) {
  74469. var GLTF2;
  74470. (function (GLTF2) {
  74471. /**
  74472. * Enums
  74473. */
  74474. var EComponentType;
  74475. (function (EComponentType) {
  74476. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  74477. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  74478. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  74479. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  74480. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  74481. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  74482. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  74483. var EMeshPrimitiveMode;
  74484. (function (EMeshPrimitiveMode) {
  74485. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  74486. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  74487. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  74488. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  74489. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  74490. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  74491. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  74492. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  74493. var ETextureMagFilter;
  74494. (function (ETextureMagFilter) {
  74495. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  74496. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  74497. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  74498. var ETextureMinFilter;
  74499. (function (ETextureMinFilter) {
  74500. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  74501. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  74502. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  74503. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  74504. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  74505. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  74506. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  74507. var ETextureWrapMode;
  74508. (function (ETextureWrapMode) {
  74509. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  74510. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  74511. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  74512. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  74513. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  74514. })(BABYLON || (BABYLON = {}));
  74515. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  74516. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74517. var BABYLON;
  74518. (function (BABYLON) {
  74519. var GLTF2;
  74520. (function (GLTF2) {
  74521. var GLTFLoader = (function () {
  74522. function GLTFLoader(parent) {
  74523. this._renderReady = false;
  74524. this._disposed = false;
  74525. this._blockPendingTracking = false;
  74526. // Observable with boolean indicating success or error.
  74527. this._renderReadyObservable = new BABYLON.Observable();
  74528. // Count of pending work that needs to complete before the asset is rendered.
  74529. this._renderPendingCount = 0;
  74530. // Count of pending work that needs to complete before the loader is cleared.
  74531. this._loaderPendingCount = 0;
  74532. this._parent = parent;
  74533. }
  74534. GLTFLoader.RegisterExtension = function (extension) {
  74535. if (GLTFLoader.Extensions[extension.name]) {
  74536. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  74537. return;
  74538. }
  74539. GLTFLoader.Extensions[extension.name] = extension;
  74540. // Keep the order of registration so that extensions registered first are called first.
  74541. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  74542. };
  74543. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  74544. get: function () {
  74545. return this._gltf;
  74546. },
  74547. enumerable: true,
  74548. configurable: true
  74549. });
  74550. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  74551. get: function () {
  74552. return this._babylonScene;
  74553. },
  74554. enumerable: true,
  74555. configurable: true
  74556. });
  74557. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  74558. if (this._renderReady) {
  74559. func();
  74560. }
  74561. else {
  74562. this._renderReadyObservable.add(func);
  74563. }
  74564. };
  74565. GLTFLoader.prototype.dispose = function () {
  74566. if (this._disposed) {
  74567. return;
  74568. }
  74569. this._disposed = true;
  74570. // Revoke object urls created during load
  74571. if (this._gltf.textures) {
  74572. this._gltf.textures.forEach(function (texture) {
  74573. if (texture.url) {
  74574. URL.revokeObjectURL(texture.url);
  74575. }
  74576. });
  74577. }
  74578. this._gltf = undefined;
  74579. this._babylonScene = undefined;
  74580. this._rootUrl = undefined;
  74581. this._defaultMaterial = undefined;
  74582. this._successCallback = undefined;
  74583. this._errorCallback = undefined;
  74584. this._renderReady = false;
  74585. this._renderReadyObservable.clear();
  74586. this._renderPendingCount = 0;
  74587. this._loaderPendingCount = 0;
  74588. };
  74589. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74590. var _this = this;
  74591. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  74592. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  74593. }, onProgress, onError);
  74594. };
  74595. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  74596. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  74597. };
  74598. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74599. this._loadData(data);
  74600. this._babylonScene = scene;
  74601. this._rootUrl = rootUrl;
  74602. this._successCallback = onSuccess;
  74603. this._progressCallback = onProgress;
  74604. this._errorCallback = onError;
  74605. this.addPendingData(this);
  74606. this._loadScene(nodeNames);
  74607. this._loadAnimations();
  74608. this.removePendingData(this);
  74609. };
  74610. GLTFLoader.prototype._onError = function (message) {
  74611. this._errorCallback(message);
  74612. this.dispose();
  74613. };
  74614. GLTFLoader.prototype._onProgress = function (event) {
  74615. this._progressCallback(event);
  74616. };
  74617. GLTFLoader.prototype._onRenderReady = function () {
  74618. switch (this._parent.coordinateSystemMode) {
  74619. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  74620. if (!this._babylonScene.useRightHandedSystem) {
  74621. this._addRightHandToLeftHandRootTransform();
  74622. }
  74623. break;
  74624. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  74625. // do nothing
  74626. break;
  74627. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  74628. this._babylonScene.useRightHandedSystem = true;
  74629. break;
  74630. default:
  74631. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  74632. break;
  74633. }
  74634. this._showMeshes();
  74635. this._startAnimations();
  74636. this._successCallback();
  74637. this._renderReadyObservable.notifyObservers(this);
  74638. };
  74639. GLTFLoader.prototype._onLoaderComplete = function () {
  74640. if (this._parent.onComplete) {
  74641. this._parent.onComplete();
  74642. }
  74643. };
  74644. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  74645. if (this._parent.onFirstLODComplete) {
  74646. this._parent.onFirstLODComplete();
  74647. }
  74648. };
  74649. GLTFLoader.prototype._loadData = function (data) {
  74650. this._gltf = data.json;
  74651. var binaryBuffer;
  74652. var buffers = this._gltf.buffers;
  74653. if (buffers && buffers[0].uri === undefined) {
  74654. binaryBuffer = buffers[0];
  74655. }
  74656. if (data.bin) {
  74657. if (binaryBuffer) {
  74658. if (binaryBuffer.byteLength != data.bin.byteLength) {
  74659. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  74660. }
  74661. }
  74662. else {
  74663. BABYLON.Tools.Warn("Unexpected BIN chunk");
  74664. }
  74665. binaryBuffer.loadedData = data.bin;
  74666. }
  74667. };
  74668. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  74669. this._rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  74670. this._rootMesh.isVisible = false;
  74671. this._rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  74672. this._rootMesh.rotation.y = Math.PI;
  74673. var nodes = this._gltf.nodes;
  74674. if (nodes) {
  74675. for (var i = 0; i < nodes.length; i++) {
  74676. var mesh = nodes[i].babylonMesh;
  74677. if (mesh && !mesh.parent) {
  74678. mesh.parent = this._rootMesh;
  74679. }
  74680. }
  74681. }
  74682. };
  74683. GLTFLoader.prototype._getMeshes = function () {
  74684. var meshes = [];
  74685. if (this._rootMesh) {
  74686. meshes.push(this._rootMesh);
  74687. }
  74688. var nodes = this._gltf.nodes;
  74689. if (nodes) {
  74690. nodes.forEach(function (node) {
  74691. if (node.babylonMesh) {
  74692. meshes.push(node.babylonMesh);
  74693. }
  74694. });
  74695. }
  74696. return meshes;
  74697. };
  74698. GLTFLoader.prototype._getSkeletons = function () {
  74699. var skeletons = [];
  74700. var skins = this._gltf.skins;
  74701. if (skins) {
  74702. skins.forEach(function (skin) {
  74703. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  74704. skeletons.push(skin.babylonSkeleton);
  74705. }
  74706. });
  74707. }
  74708. return skeletons;
  74709. };
  74710. GLTFLoader.prototype._getAnimationTargets = function () {
  74711. var targets = [];
  74712. var animations = this._gltf.animations;
  74713. if (animations) {
  74714. animations.forEach(function (animation) {
  74715. targets.push.apply(targets, animation.targets);
  74716. });
  74717. }
  74718. return targets;
  74719. };
  74720. GLTFLoader.prototype._showMeshes = function () {
  74721. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  74722. };
  74723. GLTFLoader.prototype._startAnimations = function () {
  74724. var _this = this;
  74725. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  74726. };
  74727. GLTFLoader.prototype._loadScene = function (nodeNames) {
  74728. var _this = this;
  74729. var scene = this._gltf.scenes[this._gltf.scene || 0];
  74730. var nodeIndices = scene.nodes;
  74731. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  74732. node.index = index;
  74733. node.parent = parentNode;
  74734. return true;
  74735. });
  74736. var materials = this._gltf.materials;
  74737. if (materials) {
  74738. materials.forEach(function (material, index) { return material.index = index; });
  74739. }
  74740. if (nodeNames) {
  74741. if (!(nodeNames instanceof Array)) {
  74742. nodeNames = [nodeNames];
  74743. }
  74744. var filteredNodeIndices = new Array();
  74745. this._traverseNodes(nodeIndices, function (node) {
  74746. if (nodeNames.indexOf(node.name) === -1) {
  74747. return true;
  74748. }
  74749. filteredNodeIndices.push(node.index);
  74750. return false;
  74751. });
  74752. nodeIndices = filteredNodeIndices;
  74753. }
  74754. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  74755. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  74756. };
  74757. GLTFLoader.prototype._loadSkin = function (node) {
  74758. var _this = this;
  74759. if (node.skin !== undefined) {
  74760. var skin = this._gltf.skins[node.skin];
  74761. var skeletonId = "skeleton" + node.skin;
  74762. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  74763. skin.index = node.skin;
  74764. for (var i = 0; i < skin.joints.length; i++) {
  74765. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  74766. }
  74767. if (skin.skeleton === undefined) {
  74768. // TODO: handle when skeleton is not defined
  74769. throw new Error("Not implemented");
  74770. }
  74771. if (skin.inverseBindMatrices === undefined) {
  74772. // TODO: handle when inverse bind matrices are not defined
  74773. throw new Error("Not implemented");
  74774. }
  74775. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  74776. this._loadAccessorAsync(accessor, function (data) {
  74777. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  74778. });
  74779. }
  74780. return true;
  74781. };
  74782. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  74783. var jointIndex = skin.joints.indexOf(node.index);
  74784. if (jointIndex === -1) {
  74785. this._createBone(node, skin);
  74786. }
  74787. var babylonBone = node.babylonSkinToBones[skin.index];
  74788. // TODO: explain the math
  74789. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  74790. matrix.invertToRef(matrix);
  74791. if (parentNode) {
  74792. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  74793. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  74794. }
  74795. babylonBone.updateMatrix(matrix);
  74796. return true;
  74797. };
  74798. GLTFLoader.prototype._createBone = function (node, skin) {
  74799. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  74800. node.babylonSkinToBones = node.babylonSkinToBones || {};
  74801. node.babylonSkinToBones[skin.index] = babylonBone;
  74802. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  74803. node.babylonAnimationTargets.push(babylonBone);
  74804. return babylonBone;
  74805. };
  74806. GLTFLoader.prototype._loadMesh = function (node) {
  74807. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  74808. babylonMesh.isVisible = false;
  74809. this._loadTransform(node, babylonMesh);
  74810. if (node.mesh !== undefined) {
  74811. var mesh = this._gltf.meshes[node.mesh];
  74812. this._loadMeshData(node, mesh, babylonMesh);
  74813. }
  74814. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  74815. node.babylonMesh = babylonMesh;
  74816. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  74817. node.babylonAnimationTargets.push(node.babylonMesh);
  74818. if (node.skin !== undefined) {
  74819. var skin = this._gltf.skins[node.skin];
  74820. babylonMesh.skeleton = skin.babylonSkeleton;
  74821. }
  74822. if (node.camera !== undefined) {
  74823. // TODO: handle cameras
  74824. }
  74825. return true;
  74826. };
  74827. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  74828. var _this = this;
  74829. babylonMesh.name = mesh.name || babylonMesh.name;
  74830. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  74831. babylonMesh.material = babylonMultiMaterial;
  74832. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  74833. var vertexData = new BABYLON.VertexData();
  74834. vertexData.positions = [];
  74835. vertexData.indices = [];
  74836. var subMeshInfos = [];
  74837. var loadedPrimitives = 0;
  74838. var totalPrimitives = mesh.primitives.length;
  74839. var _loop_1 = function (i) {
  74840. var primitive = mesh.primitives[i];
  74841. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  74842. // TODO: handle other primitive modes
  74843. throw new Error("Not implemented");
  74844. }
  74845. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  74846. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  74847. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  74848. subMeshInfos.push({
  74849. materialIndex: i,
  74850. verticesStart: vertexData.positions.length,
  74851. verticesCount: subVertexData.positions.length,
  74852. indicesStart: vertexData.indices.length,
  74853. indicesCount: subVertexData.indices.length,
  74854. loadMaterial: function () {
  74855. if (primitive.material === undefined) {
  74856. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  74857. }
  74858. else {
  74859. var material = _this._gltf.materials[primitive.material];
  74860. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  74861. if (isNew && _this._parent.onMaterialLoaded) {
  74862. _this._parent.onMaterialLoaded(babylonMaterial);
  74863. }
  74864. if (_this._parent.onBeforeMaterialReadyAsync) {
  74865. _this.addLoaderPendingData(material);
  74866. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  74867. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  74868. _this.removeLoaderPendingData(material);
  74869. });
  74870. }
  74871. else {
  74872. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  74873. }
  74874. });
  74875. }
  74876. }
  74877. });
  74878. vertexData.merge(subVertexData);
  74879. if (++loadedPrimitives === totalPrimitives) {
  74880. geometry.setAllVerticesData(vertexData, false);
  74881. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  74882. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  74883. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  74884. babylonMesh.subMeshes = [];
  74885. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  74886. }
  74887. });
  74888. };
  74889. var this_1 = this;
  74890. for (var i = 0; i < totalPrimitives; i++) {
  74891. _loop_1(i);
  74892. }
  74893. };
  74894. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  74895. var _this = this;
  74896. var attributes = primitive.attributes;
  74897. if (!attributes) {
  74898. this._onError("Primitive has no attributes");
  74899. return;
  74900. }
  74901. var vertexData = new BABYLON.VertexData();
  74902. var loadedAttributes = 0;
  74903. var totalAttributes = Object.keys(attributes).length;
  74904. var _loop_2 = function (semantic) {
  74905. accessor = this_2._gltf.accessors[attributes[semantic]];
  74906. this_2._loadAccessorAsync(accessor, function (data) {
  74907. switch (semantic) {
  74908. case "NORMAL":
  74909. vertexData.normals = data;
  74910. break;
  74911. case "POSITION":
  74912. vertexData.positions = data;
  74913. break;
  74914. case "TANGENT":
  74915. vertexData.tangents = data;
  74916. break;
  74917. case "TEXCOORD_0":
  74918. vertexData.uvs = data;
  74919. break;
  74920. case "TEXCOORD_1":
  74921. vertexData.uvs2 = data;
  74922. break;
  74923. case "JOINTS_0":
  74924. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  74925. break;
  74926. case "WEIGHTS_0":
  74927. vertexData.matricesWeights = data;
  74928. break;
  74929. case "COLOR_0":
  74930. vertexData.colors = data;
  74931. break;
  74932. default:
  74933. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  74934. break;
  74935. }
  74936. if (++loadedAttributes === totalAttributes) {
  74937. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  74938. if (indicesAccessor) {
  74939. _this._loadAccessorAsync(indicesAccessor, function (data) {
  74940. vertexData.indices = data;
  74941. onSuccess(vertexData);
  74942. });
  74943. }
  74944. else {
  74945. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  74946. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  74947. onSuccess(vertexData);
  74948. }
  74949. }
  74950. });
  74951. };
  74952. var this_2 = this, accessor;
  74953. for (var semantic in attributes) {
  74954. _loop_2(semantic);
  74955. }
  74956. };
  74957. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  74958. var targets = primitive.targets;
  74959. if (!targets) {
  74960. return;
  74961. }
  74962. if (!babylonMesh.morphTargetManager) {
  74963. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  74964. }
  74965. for (var index = 0; index < targets.length; index++) {
  74966. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  74967. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  74968. }
  74969. };
  74970. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  74971. var targets = primitive.targets;
  74972. if (!targets) {
  74973. return;
  74974. }
  74975. var _loop_3 = function () {
  74976. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  74977. attributes = targets[index];
  74978. var _loop_4 = function (semantic) {
  74979. accessor = this_3._gltf.accessors[attributes[semantic]];
  74980. this_3._loadAccessorAsync(accessor, function (data) {
  74981. if (accessor.name) {
  74982. babylonMorphTarget.name = accessor.name;
  74983. }
  74984. // glTF stores morph target information as deltas while babylon.js expects the final data.
  74985. // As a result we have to add the original data to the delta to calculate the final data.
  74986. var values = data;
  74987. switch (semantic) {
  74988. case "NORMAL":
  74989. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  74990. babylonMorphTarget.setNormals(values);
  74991. break;
  74992. case "POSITION":
  74993. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  74994. babylonMorphTarget.setPositions(values);
  74995. break;
  74996. case "TANGENT":
  74997. // Tangent data for morph targets is stored as xyz delta.
  74998. // The vertexData.tangent is stored as xyzw.
  74999. // So we need to skip every fourth vertexData.tangent.
  75000. for (var i = 0, j = 0; i < values.length; i++, j++) {
  75001. values[i] += vertexData.tangents[j];
  75002. if ((i + 1) % 3 == 0) {
  75003. j++;
  75004. }
  75005. }
  75006. babylonMorphTarget.setTangents(values);
  75007. break;
  75008. default:
  75009. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  75010. break;
  75011. }
  75012. });
  75013. };
  75014. for (var semantic in attributes) {
  75015. _loop_4(semantic);
  75016. }
  75017. };
  75018. var this_3 = this, attributes, accessor;
  75019. for (var index = 0; index < targets.length; index++) {
  75020. _loop_3();
  75021. }
  75022. };
  75023. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  75024. var position = BABYLON.Vector3.Zero();
  75025. var rotation = BABYLON.Quaternion.Identity();
  75026. var scaling = BABYLON.Vector3.One();
  75027. if (node.matrix) {
  75028. var mat = BABYLON.Matrix.FromArray(node.matrix);
  75029. mat.decompose(scaling, rotation, position);
  75030. }
  75031. else {
  75032. if (node.translation)
  75033. position = BABYLON.Vector3.FromArray(node.translation);
  75034. if (node.rotation)
  75035. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  75036. if (node.scale)
  75037. scaling = BABYLON.Vector3.FromArray(node.scale);
  75038. }
  75039. babylonMesh.position = position;
  75040. babylonMesh.rotationQuaternion = rotation;
  75041. babylonMesh.scaling = scaling;
  75042. };
  75043. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  75044. if (parentNode === void 0) { parentNode = null; }
  75045. for (var i = 0; i < indices.length; i++) {
  75046. this._traverseNode(indices[i], action, parentNode);
  75047. }
  75048. };
  75049. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  75050. if (parentNode === void 0) { parentNode = null; }
  75051. var node = this._gltf.nodes[index];
  75052. if (!action(node, index, parentNode)) {
  75053. return;
  75054. }
  75055. if (node.children) {
  75056. for (var i = 0; i < node.children.length; i++) {
  75057. this._traverseNode(node.children[i], action, node);
  75058. }
  75059. }
  75060. };
  75061. GLTFLoader.prototype._loadAnimations = function () {
  75062. var animations = this._gltf.animations;
  75063. if (!animations || animations.length === 0) {
  75064. return;
  75065. }
  75066. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  75067. var animation = animations[animationIndex];
  75068. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  75069. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  75070. }
  75071. }
  75072. };
  75073. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  75074. var channel = animation.channels[channelIndex];
  75075. var samplerIndex = channel.sampler;
  75076. var sampler = animation.samplers[samplerIndex];
  75077. var targetNode = this._gltf.nodes[channel.target.node];
  75078. if (!targetNode) {
  75079. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  75080. return;
  75081. }
  75082. var targetPath = {
  75083. "translation": "position",
  75084. "rotation": "rotationQuaternion",
  75085. "scale": "scaling",
  75086. "weights": "influence"
  75087. }[channel.target.path];
  75088. if (!targetPath) {
  75089. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  75090. return;
  75091. }
  75092. var animationType = {
  75093. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75094. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  75095. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75096. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  75097. }[targetPath];
  75098. var inputData;
  75099. var outputData;
  75100. var checkSuccess = function () {
  75101. if (!inputData || !outputData) {
  75102. return;
  75103. }
  75104. var outputBufferOffset = 0;
  75105. var getNextOutputValue = {
  75106. "position": function () {
  75107. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75108. outputBufferOffset += 3;
  75109. return value;
  75110. },
  75111. "rotationQuaternion": function () {
  75112. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  75113. outputBufferOffset += 4;
  75114. return value;
  75115. },
  75116. "scaling": function () {
  75117. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75118. outputBufferOffset += 3;
  75119. return value;
  75120. },
  75121. "influence": function () {
  75122. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  75123. var value = new Array(numTargets);
  75124. for (var i = 0; i < numTargets; i++) {
  75125. value[i] = outputData[outputBufferOffset++];
  75126. }
  75127. return value;
  75128. },
  75129. }[targetPath];
  75130. var getNextKey = {
  75131. "LINEAR": function (frameIndex) { return ({
  75132. frame: inputData[frameIndex],
  75133. value: getNextOutputValue()
  75134. }); },
  75135. "CUBICSPLINE": function (frameIndex) { return ({
  75136. frame: inputData[frameIndex],
  75137. inTangent: getNextOutputValue(),
  75138. value: getNextOutputValue(),
  75139. outTangent: getNextOutputValue()
  75140. }); },
  75141. }[sampler.interpolation];
  75142. var keys = new Array(inputData.length);
  75143. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  75144. keys[frameIndex] = getNextKey(frameIndex);
  75145. }
  75146. animation.targets = animation.targets || [];
  75147. if (targetPath === "influence") {
  75148. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  75149. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  75150. var morphTarget = morphTargetManager.getTarget(targetIndex);
  75151. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  75152. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  75153. babylonAnimation.setKeys(keys.map(function (key) { return ({
  75154. frame: key.frame,
  75155. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  75156. value: key.value[targetIndex],
  75157. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  75158. }); }));
  75159. morphTarget.animations.push(babylonAnimation);
  75160. animation.targets.push(morphTarget);
  75161. }
  75162. }
  75163. else {
  75164. var animationName = animation.name || "anim" + animationIndex;
  75165. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  75166. babylonAnimation.setKeys(keys);
  75167. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  75168. var target = targetNode.babylonAnimationTargets[i];
  75169. target.animations.push(babylonAnimation.clone());
  75170. animation.targets.push(target);
  75171. }
  75172. }
  75173. };
  75174. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  75175. inputData = data;
  75176. checkSuccess();
  75177. });
  75178. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  75179. outputData = data;
  75180. checkSuccess();
  75181. });
  75182. };
  75183. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  75184. var _this = this;
  75185. var buffer = this._gltf.buffers[index];
  75186. this.addPendingData(buffer);
  75187. if (buffer.loadedData) {
  75188. setTimeout(function () {
  75189. onSuccess(buffer.loadedData);
  75190. _this.removePendingData(buffer);
  75191. });
  75192. }
  75193. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  75194. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  75195. buffer.loadedData = new Uint8Array(data);
  75196. setTimeout(function () {
  75197. onSuccess(buffer.loadedData);
  75198. _this.removePendingData(buffer);
  75199. });
  75200. }
  75201. else if (buffer.loadedObservable) {
  75202. buffer.loadedObservable.add(function (buffer) {
  75203. onSuccess(buffer.loadedData);
  75204. _this.removePendingData(buffer);
  75205. });
  75206. }
  75207. else {
  75208. buffer.loadedObservable = new BABYLON.Observable();
  75209. buffer.loadedObservable.add(function (buffer) {
  75210. onSuccess(buffer.loadedData);
  75211. _this.removePendingData(buffer);
  75212. });
  75213. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  75214. buffer.loadedData = new Uint8Array(data);
  75215. buffer.loadedObservable.notifyObservers(buffer);
  75216. buffer.loadedObservable = null;
  75217. }, function (event) {
  75218. if (!_this._disposed) {
  75219. _this._onProgress(event);
  75220. }
  75221. }, this._babylonScene.database, true, function (request) {
  75222. if (!_this._disposed) {
  75223. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  75224. _this.removePendingData(buffer);
  75225. }
  75226. });
  75227. }
  75228. };
  75229. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75230. if (!byteStride) {
  75231. return new Int8Array(buffer, byteOffset, byteLength);
  75232. }
  75233. var sourceBuffer = new Int8Array(buffer, byteOffset);
  75234. var targetBuffer = new Int8Array(byteLength);
  75235. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  75236. return targetBuffer;
  75237. };
  75238. GLTFLoader.prototype._buildUint8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75239. if (!byteStride) {
  75240. return new Uint8Array(buffer, byteOffset, byteLength);
  75241. }
  75242. var sourceBuffer = new Uint8Array(buffer, byteOffset);
  75243. var targetBuffer = new Uint8Array(byteLength);
  75244. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  75245. return targetBuffer;
  75246. };
  75247. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75248. if (!byteStride) {
  75249. return new Int16Array(buffer, byteOffset, byteLength);
  75250. }
  75251. var sourceBuffer = new Int16Array(buffer, byteOffset);
  75252. var targetBuffer = new Int16Array(byteLength);
  75253. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  75254. return targetBuffer;
  75255. };
  75256. GLTFLoader.prototype._buildUint16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75257. if (!byteStride) {
  75258. return new Uint16Array(buffer, byteOffset, byteLength);
  75259. }
  75260. var sourceBuffer = new Uint16Array(buffer, byteOffset);
  75261. var targetBuffer = new Uint16Array(byteLength);
  75262. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  75263. return targetBuffer;
  75264. };
  75265. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75266. if (!byteStride) {
  75267. return new Uint32Array(buffer, byteOffset, byteLength);
  75268. }
  75269. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  75270. var targetBuffer = new Uint32Array(byteLength);
  75271. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  75272. return targetBuffer;
  75273. };
  75274. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75275. if (!byteStride) {
  75276. return new Float32Array(buffer, byteOffset, byteLength);
  75277. }
  75278. var sourceBuffer = new Float32Array(buffer, byteOffset);
  75279. var targetBuffer = new Float32Array(byteLength);
  75280. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  75281. return targetBuffer;
  75282. };
  75283. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  75284. var tempIndex = 0;
  75285. var sourceIndex = 0;
  75286. var storageSize = bytePerComponent;
  75287. while (tempIndex < length) {
  75288. for (var cursor = 0; cursor < storageSize; cursor++) {
  75289. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  75290. tempIndex++;
  75291. }
  75292. sourceIndex += stride;
  75293. }
  75294. };
  75295. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  75296. var _this = this;
  75297. byteOffset += (bufferView.byteOffset || 0);
  75298. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  75299. if (byteOffset + byteLength > bufferData.byteLength) {
  75300. _this._onError("Buffer access is out of range");
  75301. return;
  75302. }
  75303. var buffer = bufferData.buffer;
  75304. byteOffset += bufferData.byteOffset;
  75305. var bufferViewData;
  75306. switch (componentType) {
  75307. case GLTF2.EComponentType.BYTE:
  75308. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75309. break;
  75310. case GLTF2.EComponentType.UNSIGNED_BYTE:
  75311. bufferViewData = _this._buildUint8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75312. break;
  75313. case GLTF2.EComponentType.SHORT:
  75314. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75315. break;
  75316. case GLTF2.EComponentType.UNSIGNED_SHORT:
  75317. bufferViewData = _this._buildUint16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75318. break;
  75319. case GLTF2.EComponentType.UNSIGNED_INT:
  75320. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75321. break;
  75322. case GLTF2.EComponentType.FLOAT:
  75323. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75324. break;
  75325. default:
  75326. _this._onError("Invalid component type (" + componentType + ")");
  75327. return;
  75328. }
  75329. onSuccess(bufferViewData);
  75330. });
  75331. };
  75332. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  75333. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  75334. var byteOffset = accessor.byteOffset || 0;
  75335. var bytePerComponent = this._getByteStrideFromType(accessor);
  75336. var byteLength = accessor.count * bytePerComponent;
  75337. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  75338. };
  75339. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  75340. switch (accessor.type) {
  75341. case "SCALAR": return 1;
  75342. case "VEC2": return 2;
  75343. case "VEC3": return 3;
  75344. case "VEC4": return 4;
  75345. case "MAT2": return 4;
  75346. case "MAT3": return 9;
  75347. case "MAT4": return 16;
  75348. default:
  75349. this._onError("Invalid accessor type (" + accessor.type + ")");
  75350. return 0;
  75351. }
  75352. };
  75353. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  75354. set: function (value) {
  75355. this._blockPendingTracking = value;
  75356. },
  75357. enumerable: true,
  75358. configurable: true
  75359. });
  75360. GLTFLoader.prototype.addPendingData = function (data) {
  75361. if (!this._renderReady) {
  75362. this._renderPendingCount++;
  75363. }
  75364. this.addLoaderPendingData(data);
  75365. };
  75366. GLTFLoader.prototype.removePendingData = function (data) {
  75367. if (!this._renderReady) {
  75368. if (--this._renderPendingCount === 0) {
  75369. this._renderReady = true;
  75370. this._onRenderReady();
  75371. }
  75372. }
  75373. this.removeLoaderPendingData(data);
  75374. };
  75375. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  75376. if (!this._nonBlockingData) {
  75377. this._nonBlockingData = new Array();
  75378. }
  75379. this._nonBlockingData.push(data);
  75380. };
  75381. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  75382. if (this._blockPendingTracking) {
  75383. this.addLoaderNonBlockingPendingData(data);
  75384. return;
  75385. }
  75386. this._loaderPendingCount++;
  75387. };
  75388. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  75389. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  75390. if (indexInPending !== -1) {
  75391. this._nonBlockingData.splice(indexInPending, 1);
  75392. }
  75393. else if (--this._loaderPendingCount === 0) {
  75394. this._onLoaderFirstLODComplete();
  75395. }
  75396. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  75397. this._onLoaderComplete();
  75398. this.dispose();
  75399. }
  75400. };
  75401. GLTFLoader.prototype._getDefaultMaterial = function () {
  75402. if (!this._defaultMaterial) {
  75403. var id = "__gltf_default";
  75404. var material = this._babylonScene.getMaterialByName(id);
  75405. if (!material) {
  75406. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  75407. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75408. material.metallic = 1;
  75409. material.roughness = 1;
  75410. }
  75411. this._defaultMaterial = material;
  75412. }
  75413. return this._defaultMaterial;
  75414. };
  75415. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  75416. var babylonMaterial = material.babylonMaterial;
  75417. // Ensure metallic workflow
  75418. babylonMaterial.metallic = 1;
  75419. babylonMaterial.roughness = 1;
  75420. var properties = material.pbrMetallicRoughness;
  75421. if (!properties) {
  75422. return;
  75423. }
  75424. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  75425. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  75426. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  75427. if (properties.baseColorTexture) {
  75428. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  75429. }
  75430. if (properties.metallicRoughnessTexture) {
  75431. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  75432. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  75433. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  75434. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  75435. }
  75436. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  75437. };
  75438. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  75439. if (material.babylonMaterial) {
  75440. assign(material.babylonMaterial, false);
  75441. return;
  75442. }
  75443. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  75444. return;
  75445. }
  75446. this.createPbrMaterial(material);
  75447. this.loadMaterialBaseProperties(material);
  75448. this._loadMaterialMetallicRoughnessProperties(material);
  75449. assign(material.babylonMaterial, true);
  75450. };
  75451. GLTFLoader.prototype.createPbrMaterial = function (material) {
  75452. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  75453. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75454. material.babylonMaterial = babylonMaterial;
  75455. };
  75456. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  75457. var babylonMaterial = material.babylonMaterial;
  75458. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  75459. if (material.doubleSided) {
  75460. babylonMaterial.backFaceCulling = false;
  75461. babylonMaterial.twoSidedLighting = true;
  75462. }
  75463. if (material.normalTexture) {
  75464. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  75465. babylonMaterial.invertNormalMapX = true;
  75466. babylonMaterial.invertNormalMapY = false;
  75467. if (material.normalTexture.scale !== undefined) {
  75468. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  75469. }
  75470. }
  75471. if (material.occlusionTexture) {
  75472. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  75473. babylonMaterial.useAmbientInGrayScale = true;
  75474. if (material.occlusionTexture.strength !== undefined) {
  75475. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  75476. }
  75477. }
  75478. if (material.emissiveTexture) {
  75479. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  75480. }
  75481. };
  75482. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  75483. var babylonMaterial = material.babylonMaterial;
  75484. var alphaMode = material.alphaMode || "OPAQUE";
  75485. switch (alphaMode) {
  75486. case "OPAQUE":
  75487. // default is opaque
  75488. break;
  75489. case "MASK":
  75490. case "BLEND":
  75491. if (colorFactor) {
  75492. babylonMaterial.alpha = colorFactor[3];
  75493. }
  75494. if (babylonMaterial.albedoTexture) {
  75495. babylonMaterial.albedoTexture.hasAlpha = true;
  75496. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  75497. }
  75498. break;
  75499. default:
  75500. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  75501. break;
  75502. }
  75503. babylonMaterial.alphaCutOff = material.alphaCutoff === undefined ? 0.5 : material.alphaCutoff;
  75504. };
  75505. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  75506. var _this = this;
  75507. var texture = this._gltf.textures[textureInfo.index];
  75508. var texCoord = textureInfo.texCoord || 0;
  75509. if (!texture || texture.source === undefined) {
  75510. return null;
  75511. }
  75512. var source = this._gltf.images[texture.source];
  75513. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  75514. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  75515. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  75516. this.addPendingData(texture);
  75517. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  75518. if (!_this._disposed) {
  75519. _this.removePendingData(texture);
  75520. }
  75521. }, function () {
  75522. if (!_this._disposed) {
  75523. _this._onError("Failed to load texture '" + source.uri + "'");
  75524. _this.removePendingData(texture);
  75525. }
  75526. });
  75527. if (texture.url) {
  75528. babylonTexture.updateURL(texture.url);
  75529. }
  75530. else if (texture.dataReadyObservable) {
  75531. texture.dataReadyObservable.add(function (texture) {
  75532. babylonTexture.updateURL(texture.url);
  75533. });
  75534. }
  75535. else {
  75536. texture.dataReadyObservable = new BABYLON.Observable();
  75537. texture.dataReadyObservable.add(function (texture) {
  75538. babylonTexture.updateURL(texture.url);
  75539. });
  75540. var setTextureData = function (data) {
  75541. texture.url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  75542. texture.dataReadyObservable.notifyObservers(texture);
  75543. };
  75544. if (!source.uri) {
  75545. var bufferView = this._gltf.bufferViews[source.bufferView];
  75546. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  75547. }
  75548. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  75549. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  75550. }
  75551. else {
  75552. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  75553. if (!_this._disposed) {
  75554. _this._onProgress(event);
  75555. }
  75556. }, this._babylonScene.database, true, function (request) {
  75557. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  75558. });
  75559. }
  75560. }
  75561. babylonTexture.coordinatesIndex = texCoord;
  75562. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  75563. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  75564. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  75565. if (this._parent.onTextureLoaded) {
  75566. this._parent.onTextureLoaded(babylonTexture);
  75567. }
  75568. return babylonTexture;
  75569. };
  75570. GLTFLoader.Extensions = {};
  75571. return GLTFLoader;
  75572. }());
  75573. GLTF2.GLTFLoader = GLTFLoader;
  75574. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  75575. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75576. })(BABYLON || (BABYLON = {}));
  75577. //# sourceMappingURL=babylon.glTFLoader.js.map
  75578. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75579. var BABYLON;
  75580. (function (BABYLON) {
  75581. var GLTF2;
  75582. (function (GLTF2) {
  75583. /**
  75584. * Utils functions for GLTF
  75585. */
  75586. var GLTFUtils = (function () {
  75587. function GLTFUtils() {
  75588. }
  75589. /**
  75590. * If the uri is a base64 string
  75591. * @param uri: the uri to test
  75592. */
  75593. GLTFUtils.IsBase64 = function (uri) {
  75594. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  75595. };
  75596. /**
  75597. * Decode the base64 uri
  75598. * @param uri: the uri to decode
  75599. */
  75600. GLTFUtils.DecodeBase64 = function (uri) {
  75601. var decodedString = atob(uri.split(",")[1]);
  75602. var bufferLength = decodedString.length;
  75603. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  75604. for (var i = 0; i < bufferLength; i++) {
  75605. bufferView[i] = decodedString.charCodeAt(i);
  75606. }
  75607. return bufferView.buffer;
  75608. };
  75609. GLTFUtils.ForEach = function (view, func) {
  75610. for (var index = 0; index < view.length; index++) {
  75611. func(view[index], index);
  75612. }
  75613. };
  75614. GLTFUtils.GetTextureWrapMode = function (mode) {
  75615. // Set defaults if undefined
  75616. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  75617. switch (mode) {
  75618. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  75619. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  75620. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  75621. default:
  75622. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  75623. return BABYLON.Texture.WRAP_ADDRESSMODE;
  75624. }
  75625. };
  75626. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  75627. // Set defaults if undefined
  75628. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  75629. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  75630. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  75631. switch (minFilter) {
  75632. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  75633. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  75634. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  75635. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  75636. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  75637. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  75638. default:
  75639. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  75640. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  75641. }
  75642. }
  75643. else {
  75644. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  75645. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  75646. }
  75647. switch (minFilter) {
  75648. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  75649. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  75650. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  75651. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  75652. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  75653. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  75654. default:
  75655. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  75656. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  75657. }
  75658. }
  75659. };
  75660. /**
  75661. * Decodes a buffer view into a string
  75662. * @param view: the buffer view
  75663. */
  75664. GLTFUtils.DecodeBufferToText = function (view) {
  75665. var result = "";
  75666. var length = view.byteLength;
  75667. for (var i = 0; i < length; ++i) {
  75668. result += String.fromCharCode(view[i]);
  75669. }
  75670. return result;
  75671. };
  75672. return GLTFUtils;
  75673. }());
  75674. GLTF2.GLTFUtils = GLTFUtils;
  75675. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75676. })(BABYLON || (BABYLON = {}));
  75677. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  75678. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75679. var BABYLON;
  75680. (function (BABYLON) {
  75681. var GLTF2;
  75682. (function (GLTF2) {
  75683. var GLTFLoaderExtension = (function () {
  75684. function GLTFLoaderExtension() {
  75685. this.enabled = true;
  75686. }
  75687. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  75688. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  75689. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  75690. };
  75691. GLTFLoaderExtension._ApplyExtensions = function (action) {
  75692. var extensions = GLTFLoaderExtension._Extensions;
  75693. if (!extensions) {
  75694. return;
  75695. }
  75696. for (var i = 0; i < extensions.length; i++) {
  75697. var extension = extensions[i];
  75698. if (extension.enabled && action(extension)) {
  75699. return true;
  75700. }
  75701. }
  75702. return false;
  75703. };
  75704. //
  75705. // Utilities
  75706. //
  75707. GLTFLoaderExtension._Extensions = [];
  75708. return GLTFLoaderExtension;
  75709. }());
  75710. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  75711. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75712. })(BABYLON || (BABYLON = {}));
  75713. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  75714. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  75715. var BABYLON;
  75716. (function (BABYLON) {
  75717. var GLTF2;
  75718. (function (GLTF2) {
  75719. var Extensions;
  75720. (function (Extensions) {
  75721. var MSFTLOD = (function (_super) {
  75722. __extends(MSFTLOD, _super);
  75723. function MSFTLOD() {
  75724. return _super !== null && _super.apply(this, arguments) || this;
  75725. }
  75726. Object.defineProperty(MSFTLOD.prototype, "name", {
  75727. get: function () {
  75728. return "MSFT_lod";
  75729. },
  75730. enumerable: true,
  75731. configurable: true
  75732. });
  75733. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  75734. if (!material.extensions) {
  75735. return false;
  75736. }
  75737. var properties = material.extensions[this.name];
  75738. if (!properties) {
  75739. return false;
  75740. }
  75741. // Clear out the extension so that it won't get loaded again.
  75742. material.extensions[this.name] = undefined;
  75743. // Tell the loader not to clear its state until the highest LOD is loaded.
  75744. var materialLODs = [material.index].concat(properties.ids);
  75745. loader.addLoaderPendingData(material);
  75746. for (var index = 0; index < materialLODs.length; index++) {
  75747. loader.addLoaderNonBlockingPendingData(index);
  75748. }
  75749. // Start with the lowest quality LOD.
  75750. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  75751. return true;
  75752. };
  75753. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  75754. var _this = this;
  75755. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  75756. if (lod !== materialLODs.length - 1) {
  75757. loader.blockPendingTracking = true;
  75758. }
  75759. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  75760. assign(babylonMaterial, isNew);
  75761. loader.removeLoaderPendingData(lod);
  75762. // Loading is considered complete if this is the lowest quality LOD.
  75763. if (lod === materialLODs.length - 1) {
  75764. loader.removeLoaderPendingData(material);
  75765. }
  75766. if (lod === 0) {
  75767. loader.blockPendingTracking = false;
  75768. return;
  75769. }
  75770. // Load the next LOD when the loader is ready to render and
  75771. // all active material textures of the current LOD are loaded.
  75772. loader.executeWhenRenderReady(function () {
  75773. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  75774. setTimeout(function () {
  75775. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  75776. }, MSFTLOD.MinimalLODDelay);
  75777. });
  75778. });
  75779. });
  75780. };
  75781. /**
  75782. * Specify the minimal delay between LODs in ms (default = 250)
  75783. */
  75784. MSFTLOD.MinimalLODDelay = 250;
  75785. return MSFTLOD;
  75786. }(GLTF2.GLTFLoaderExtension));
  75787. Extensions.MSFTLOD = MSFTLOD;
  75788. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  75789. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  75790. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75791. })(BABYLON || (BABYLON = {}));
  75792. //# sourceMappingURL=MSFT_lod.js.map
  75793. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  75794. var BABYLON;
  75795. (function (BABYLON) {
  75796. var GLTF2;
  75797. (function (GLTF2) {
  75798. var Extensions;
  75799. (function (Extensions) {
  75800. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  75801. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  75802. function KHRMaterialsPbrSpecularGlossiness() {
  75803. return _super !== null && _super.apply(this, arguments) || this;
  75804. }
  75805. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  75806. get: function () {
  75807. return "KHR_materials_pbrSpecularGlossiness";
  75808. },
  75809. enumerable: true,
  75810. configurable: true
  75811. });
  75812. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  75813. if (!material.extensions) {
  75814. return false;
  75815. }
  75816. var properties = material.extensions[this.name];
  75817. if (!properties) {
  75818. return false;
  75819. }
  75820. loader.createPbrMaterial(material);
  75821. loader.loadMaterialBaseProperties(material);
  75822. this._loadSpecularGlossinessProperties(loader, material, properties);
  75823. assign(material.babylonMaterial, true);
  75824. return true;
  75825. };
  75826. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  75827. var babylonMaterial = material.babylonMaterial;
  75828. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  75829. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  75830. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  75831. if (properties.diffuseTexture) {
  75832. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  75833. }
  75834. if (properties.specularGlossinessTexture) {
  75835. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  75836. babylonMaterial.reflectivityTexture.hasAlpha = true;
  75837. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  75838. }
  75839. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  75840. };
  75841. return KHRMaterialsPbrSpecularGlossiness;
  75842. }(GLTF2.GLTFLoaderExtension));
  75843. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  75844. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  75845. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  75846. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75847. })(BABYLON || (BABYLON = {}));
  75848. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  75849. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  75850. module.exports = BABYLON;
  75851. };